HashSet实现Set接口(内部是HashMap),无序不重复,它不保证集合的迭代顺序。如果操作的元素是对象须重写equals和hashcode两方法来保证不重复去存,并且最多包含一个null元素。
TreeSet实现Set接口(内部是TreeMap)。有序不重复,如果TreeSet中元素是对象则必须要实现Comparable接口,否则会抛出Exception in thread "main" java.lang.ClassCastException: com.code.Student cannot be cast to java.lang.Comparable异常。
HashSet与TreeSet都是基于Set接口的实现类,其中TreeSet是Set的子接口SortedSet的实现类。
HashSet是基于Hash算法实现的,其性能通常优于TreeSet,我们通常都应该使用HashSet,在我们需要排序的功能时,我门才使用TreeSet。
HashSet示例
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("1");
set.add("2");
set.add("1");
System.out.println(set);
Set<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
set1.add(2);
set1.add(3);
System.out.println(set1);
}
HashSet集合只能存取包装类,以上代码输出如下;
[1, 2]
[1, 2, 3]
public static void main(String[] args) {
Set<Student> set = new HashSet<>();
set.add(null);
set.add(null);
set.add(new Student(20,"张山"));
set.add(new Student(20,"张山"));
set.add(new Student(40,"张山"));
System.out.println(set);
}
HashSet操作Student类,此时没有重写equals和hashcode两方法,输出如下;
[null, Student [age=40, name=张山], Student [age=20, name=张山], Student [age=20, name=张山]]
重写之后输出如下;
[null, Student [age=40, name=张山], Student [age=20, name=张山]]
TreeSet示例
public static void main(String[] args) {
Set<Student> set = new TreeSet<>();
set.add(null); //不允许null
set.add(new Student(3,"ss3"));
set.add(new Student(2,"ss2"));
set.add(new Student(1,"ss1"));
set.add(new Student(4,"ss4"));
System.out.println(set);
}
Exception in thread "main" java.lang.NullPointerException
public static void main(String[] args) {
Set<Student> set = new TreeSet<>();
set.add(new Student(3,"ss3"));
set.add(new Student(2,"ss2"));
set.add(new Student(2,"ss2"));
set.add(new Student(1,"ss1"));
set.add(new Student(4,"ss4"));
System.out.println(set);
}
[Student [age=1, name=ss1], Student [age=2, name=ss2], Student [age=3, name=ss3], Student [age=4, name=ss4]]
Student类必须实现Comparable<?>接口,重写compareTo(?)方法,否则抛出异常java.lang.ClassCastException: com.code.Student cannot be cast to java.lang.Comparable。