前言
在一些去重的场景中,经常会用到 Set 集合
Set
HashSet
HashSet 使用 hash算法来存储集合的元素,具有很好的存储和查找的性能。
特点:
- 不能保证元素的顺序
- HashSet 非线程安全
- 可以包含null
当向 HashSet 中存储一个元素时,会调用该元素的 hashCode() 方法获得其 hashCode 值,根据 hashCode 值确定其在HashSet 中的存储位置。
比如两个对象,equals 相同但是 hashCode 值不相同,那么久存储在不同的位置,所以在重写对象的 equals 方法时,也要重写其 hashCode 方法。
import java.util.HashSet;
import java.util.Set;
class A {
@Override
public boolean equals(Object obj) {
return true;
}
}
class B {
@Override
public int hashCode() {
return 2;
}
}
class C {
@Override
public int hashCode() {
return 1;
}
@Override
public boolean equals(Object obj) {
return true;
}
}
public class HashSetTest {
public static void main(String[] args) {
Set<Object> set = new HashSet<>();
set.add(new A());
set.add(new A());
set.add(new B());
set.add(new B());
set.add(new C());
set.add(new C());
System.out.println(set);
}
}
----------------------------------------------------------------------------------
[com.beng.set.C@1, com.beng.set.A@33909752, com.beng.set.B@2, com.beng.set.B@2, com.beng.set.A@55f96302]
看到输出了两个 A,两个B,一个C
A: 即使 equals 方法相同,但是HashSet依然把他们当成两个对象
B: 即使 hashCode 值一样,还是当成两个对象存储
C: 一个对象
看下 add 方法的实现,调用了 HashMap 的 put() :
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
put( )
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
重点来了:
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
先不管 HashMap 的数据结构,直接看 if else
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
其在判断的时候,既比较 hashCode 值比较 key 的值,也就是你存放的元素。
其中在 equals 为 false,但是 hashCode 值相同时,HashSet 会试图将其保存在同一个位置,其会用一个链表进行保存,这样会导致性能下降。
LinkedHashSet
使用链表维护元素的次序。
当遍历 LinkedHashSet 当中的元素时,会按元素的添加顺序来访问集合里的元素。
LinkedHashSet 性能略低于 HashSet 的性能,但是在迭代的时候性能较好。
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
public class LinkedHashSetTest {
public static void main(String[] args) {
Set<String> books = new HashSet<>();
books.add("深入理解Java虚拟机");
books.add("高性能MySQL");
books.add("鸟哥的Linux私房菜");
System.out.println(books);
Set<String> books1 = new LinkedHashSet<>();
books1.add("深入理解Java虚拟机");
books1.add("高性能MySQL");
books1.add("鸟哥的Linux私房菜");
System.out.println(books1);
}
}
--------------------------------------------------------------------
[高性能MySQL, 深入理解Java虚拟机, 鸟哥的Linux私房菜]
[深入理解Java虚拟机, 高性能MySQL, 鸟哥的Linux私房菜]
TreeSet
TreeSet 是 SortedSet 接口的实现类,确保元素处于排序的状态。
TreeSet 采用红黑树的数据结构来存储元素。
TreeSet 支持两种排序:
- 自然排序
- 定制排序
自然排序
TreeSet 会调用元素的 compareTo() 方法来比较元素之间的大小,默认升序排列
obj1.compareTo(obj2)
- 返回 0,相等
- 返回正整数, obj1 大于 obj2
- 返回负整数, obj1 小于 obj2
定制排序
通过 Comparator 接口
import java.util.Comparator;
import java.util.TreeSet;
class M {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "M [age=" + age + "]";
}
}
public class TreeSetTest {
public static void main(String[] args) {
TreeSet set = new TreeSet<>(new Comparator<M>() {
@Override
public int compare(M o1, M o2) {
return o1.getAge() > o2.getAge() ? -1 : o1.getAge() < o2.getAge() ? 1 : 0;
}
});
// TreeSet set = new TreeSet<>(
// (o1, o2) -> ((M) o1).getAge() > ((M) o2).getAge() ? -1 : ((M)
// o1).getAge() < ((M) o2).getAge() ? 1 : 0);
M m1 = new M();
m1.setAge(10);
M m2 = new M();
m2.setAge(20);
set.add(m2);
set.add(m1);
System.out.println(set);
}
}
-----------------------------------------
[M [age=20], M [age=10]]
EnumSet
EnumSet 是专门为枚举类设计的集合类,EnumSet 中的所有元素都必须制定枚举类型的枚举值。
import java.util.EnumSet;
enum Season {
SPRING, SUMMER, FALL, WINTER;
}
public class EnumSetTest {
public static void main(String[] args) {
EnumSet set = EnumSet.allOf(Season.class);
System.out.println(set);
EnumSet set1 = EnumSet.noneOf(Season.class);
System.out.println(set1);
set1.add(Season.SPRING);
set1.add(Season.SUMMER);
System.out.println(set1);
}
}
---------------------------
[SPRING, SUMMER, FALL, WINTER]
[]
[SPRING, SUMMER]
EnumSet 没有提供构造方法,全是静态方法。
Set 类性能分析
- HashSet 查询,添加性能更好
- TreeSet 需要额外的红黑树支持
- LinkedHashSet 插入,删除比 HashSet 略慢,遍历快
- EnumSet 内部以位向量的形式存储,存储形式紧凑高效,占用内存小,运行效率高
这几个Set都是非线程安全的,如果要保证线程线安全,使用:
Collections 工具类的 Collections.synchronizedXXX 方法
注意:在使用Set存储时,尽量不要使用可变对象,会引发意向不到的错误。