-
HashSet:存储数据结构以及对数据的操作主要是通过HashMap来实现的,线程不安全。HashSet判断值唯一,先通过hashCode()函数获取hash值判断相等不相等,如果相等则再调用equals方法判断。
-
LinkedHashSet:继承了HashSet。与HashSet的区别在于,HashSet的元素是无序的,而LinkedHashSet使用链表维护元素的次序,访问元素的时候会按照插入的顺序访问集合的元素
public class Test {
public static void main(String[] args) {
Student student1 = new Student("student1");
Student student2 = new Student("student2");
Student student3 = new Student("student3");
HashSet<Student> hashSet = new HashSet<>();
hashSet.add(student1);
hashSet.add(student2);
hashSet.add(student3);
LinkedHashSet<Student> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add(student1);
linkedHashSet.add(student2);
linkedHashSet.add(student3);
printSet(hashSet);
printSet(linkedHashSet);
}
public static void printSet(Set<Student> set) {
System.out.println(set.getClass());
for (Iterator iterator = set.iterator(); iterator.hasNext();) {
Student student = (Student) iterator.next();
System.out.println(student.name);
}
}
}
打印出来的结果:
class java.util.HashSet
student3
student1
student2
class java.util.LinkedHashSet
student1
student2
student3
-
TreeSet:实现了SortSet的接口,可以看出集合的元素是出于排序状态的,放入TreeSet中的对象需实现Comparable接口并覆盖其compareTo()方法。有自然排序和定制排序,默认使用自然排序,如果元素不是自定义的对象,那么会按照升序排列。
public class Test {
public static void main(String[] args) {
Student student1 = new Student("student1");
Student student2 = new Student("student2");
Student student3 = new Student("student3");
TreeSet<Student> treeSet = new TreeSet<>();
treeSet.add(student1);
treeSet.add(student3);
treeSet.add(student2);
printSet(treeSet);
TreeSet<Student> treeSet2 = new TreeSet<>(new StudentComparator());
treeSet2.add(student1);
treeSet2.add(student3);
treeSet2.add(student2);
printSet(treeSet2);
}
public static void printSet(Set<Student> set) {
System.out.println(set.getClass());
for (Iterator iterator = set.iterator(); iterator.hasNext();) {
Student student = (Student) iterator.next();
System.out.println(student.name);
}
}
}
class Student implements Comparable{
public Student(String name) {
super();
this.name = name;
}
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int compareTo(Object o) {
return this.name.compareTo(((Student)o).getName());
}
}
class StudentComparator implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
return o2.getName().compareTo(o1.getName());
}
}
打印出来的结果:
class java.util.TreeSet
student1
student2
student3
class java.util.TreeSet
student3
student2
student1