Set集合
集合元素无序不重复,三个实现类都是线程不安全的,最好在创建时通过Collection工具类的synchronizedSortedSet方法来包装Set集合,防止对set集合的意外非同步访问。
HashSet类
- 按Hash算法存储元素,具有很好的存取和查找性能
- 判断相等的标准是两个对象通过equals方法比较相等,并且两个对象的hashCode方法的返回值也相等
- 集合元素可以为null
- 如果需要重写equals方法,则也需要重写hashCode方法,保证对象相等
LinkedHashSet类
- 根据元素的hashCode值决定存储位置,使用链表维护次序,以插入顺序保存,在迭代访问全部元素时有很好的性能
EnumSet类
- 元素为同类型的枚举值,有序,在内部以单位向量的形式存储,占内存小,运行效率好,尤其是进行批量操作时。
- 不允许加入null值,应该通过提供的类方法创建对象。
TreeSet类
- 集合元素按大小排序,采用红黑树的数据结构存储
- 由于每添加一个元素都要调用该对象的compareTo(Object obj)方法与集合中其他元素比较,所以TreeSet只能添加同一种类型的对象
- 判断相等的标准是通过compareTo方法比较返回0
- 提供多种方法,如:
- Object first()
- Object last()
- Object lower(Object e)
- 利用lambda表达式定制排序
import java.util.TreeSet;
public class Customer {
private String name;
private int age;
public Customer(int age) {
this.age = age;
}
public String toString() {
return "[Customer:" + age + "]";
}
public static void main(String[] args) {
TreeSet<Customer> tsCustomers = new TreeSet<>((o1,o2) -> {
Customer c1 = (Customer)o1;
Customer c2 = (Customer)o2;
return c1.age > c2.age ? -1
:c1.age < c2.age ? 1 : 0;
});
tsCustomers.add(new Customer(10));
tsCustomers.add(new Customer(20));
System.out.println(tsCustomers);
}
}
输出结果为: