集合2

来源:互联网 发布:市场花园知乎 编辑:程序博客网 时间:2024/05/29 08:57
  • HashSet

    1.元素顺序:
    元素唯一,但是无序。
    2.如何保证元素的唯一性:
    底层数据结构是哈希表。
    哈希表依赖两个方法:hashCode()和equals()

    执行流程:    首先判断哈希值是否相同,如果不同,就直接添加到集合。    如果相同,继续执行equals(),看其返回值,    如果是false,就直接添加到集合。    如果是true,说明元素重复不添加。
public static void main(String[] args) {        //创建集合        HashSet<Student> hs = new HashSet<Student>();        //创建学生对象        Student s1 = new Student("a", 5);        Student s2 = new Student("b", 4);        Student s3 = new Student("c", 6);        Student s4 = new Student("d", 7);        Student s5 = new Student("a", 5);        //给集合中添加元素        hs.add(s1);        hs.add(s2);        hs.add(s3);        hs.add(s4);        hs.add(s5);        //遍历集合        for (Student student : hs) {            System.out.println(student);        }    }

输出结果为:
Student [name=d, age=7]
Student [name=c, age=6]
Student [name=b, age=4]
Student [name=a, age=5]

可见,元素无序和元素唯一两个特点。

  • TreeSet

1.元素顺序:
使用元素的自然顺序对元素进行排序,或者根据创建 set时提供的 Comparator进行排序(比较器排序),
具体取决于使用的构造方法。
2。 底层算法:
二叉树

这里写图片描述

练习:键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低输出到控制台,用比较器实现。

public static void main(String[] args) {        System.out.println("请按格式输入学生信息:(姓名,语文成绩,数学成绩,英语成绩)");        Scanner sc = new Scanner(System.in);        //创建TreeSet对象,使用比较器排序,使用匿名内部类重写方法        TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {            @Override            public int compare(Student o1, Student o2) {                int num=o2.getGrade()-o1.getGrade();                int num2=num==0?o1.getName().compareTo(o2.getName()):num;                return num2;            }        });        //接收5次输入,并将信息加入到TreeSet        for (int i = 0; i < 5; i++) {            String next = sc.next();            String reg=",";            String[] sp = next.split(reg);            Student s = new Student(sp[0], Integer.parseInt(sp[1]), Integer.parseInt(sp[2]), Integer.parseInt(sp[3]));            ts.add(s);        }        //遍历        for (Student student : ts) {            System.out.println(student);        }    }

HashSet与TreeSet的相同点与不同点
相同点:
单列集合,元素不可重复
不同点
1. 底层存储的数据结构不同
HashSet底层用的是HashMap哈希表结构存储,而TreeSet底层用的是TreeMap树结构存储
2.存储时保证数据唯一性依据不同
HashSet是通过复写hashCode()方法和equals()方法来保证的,而TreeSet通过Compareable接口的compareTo()方法来保证的
3.有序性不一样
HashSet无序,TreeSet有序

0 0