Set集合练习

作者: 寻叶亭 | 来源:发表于2017-06-17 17:31 被阅读93次

    Collection有2个子接口:
    1.list(列表):有序,可重复

    2.set(集):无序,不可重复
    hashSet:底层数据结构是哈希表。线程不同步。通过判断元素的hashCode值是否相同保证元素的唯一。若相同,继续判断元素的equals方法

    TreeSet:底层数据结构是二叉树,通过compareTo方法保证元素唯一,两种排序方式:
    ①让元素自身具备比较性,通过实现Comparable接口,覆盖compareTo方法。也叫自然顺序、默认顺序
    ②当元素自身不具备比较性,或者具备的比较性不适用时,这时需要让集合自身初始化时就具备比较性

    Tips:排序时,当主要条件相同时,一定要再判断次要条件

    练习:往TreeSet集合中存储自定义对象学生,按照年龄排序

    import java.util.*
    public  class TreeSetDemo {
    public static void main(String[] args) {
        TreeSet ts = new TreeSet();
        ts.add(new Student("xuesheng01",23));
        ts.add(new Student("xuesheng04",13));
        ts.add(new Student("xuesheng03",13));
        ts.add(new Student("xuesheng02",9));
        
        Iterator it = ts.iterator();//使用迭代器迭代
        while (it.hasNext())
        {
            Student stu =(Student)it.next();//迭代器的next方法返回值类型是object,所以要向下转型
            System.out.println(stu.getName()+"---"+stu.getAge());
        };
    }
    public class Student implements Comparable//这里使用的是第二种方法,让集合自身具备比较性
    {
    private String name;
    private int age;
    public Student (String name, int age)
        {
        this.name = name;
        this.age = age;
        }
    public int compareTo(Object obj)
        {
        if(!(obj instanceof Student))//判断是否是学生对象实例
            throw new RuntimeException("不是学生对象");//若不是则抛出异常
        Student s = (Student)obj;
        if(this.age>s.age)//和新增对象的年龄,进行比较
            return 1;//返回正数。代表新增的年龄较小
        if(this.age==s.age)
        {
            return this.name.compareTo(s.name);//当主要条件相同,则比较次要条件
        }
        return -1;}//否则返回负数,代表新增的对象年龄较大     
    public String getName()
        {
            return name;
        }
    public int getAge()
        {
            return age;
        }   
    }}
    

    运行结果为:

    xuesheng02---9
    xuesheng03---13
    xuesheng04---13
    xuesheng01---23
    

    期间遇到报错:

      Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
       No enclosing instance of type TreeSetDemo is accessible. Must qualify the allocation with an enclosing       
       instance of type TreeSetDemo (e.g. x.new A() where x is an instance of TreeSetDemo).
        at myobject.TreeSetDemo.main(TreeSetDemo.java:13)
    
    • 问题产生原因:内部类Student是动态的,即public class开头。而主程序是public static class main。在Java中,类中的静态方法不能直接调用动态方法。只有将某个内部类修饰为静态类,然后才能够在静态类中调用该类的成员变量与成员方法。
    • 解决方案:在不做其他变动的情况下,最简单的解决办法是将public class改为public static class.

    相关文章

      网友评论

        本文标题:Set集合练习

        本文链接:https://www.haomeiwen.com/subject/bdhbqxtx.html