Set 集合最常见的实现类就是 HashSet,就以它为例来讲。底层使用的是 HashMap 进行存储数据,所以了解 HashMap 真正看懂 HashSet 源码。
1. HashSet 的定义详解
- 定义很简单,继承抽象set,实现接口Set,可复制、可序列化
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
1.1 HashSet 的构造函数
- HashSet 有五个构造函数,可以指定初始集合,初始容量,初始的负载因子,但没有三个同时指定的构造函数
/* 空构造,默认初始容量16,负载因子 0.75,后面详解 */
public HashSet() {
map = new HashMap<>();
}
/** 初始化一个集合,默认负载因子为0.75,容量看情况定义足够存储的大小 */
public HashSet(Collection<? extends E> c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}
/* 创建一个空集合,但是指定 容量大小 与 负载因子 */
public HashSet(int initialCapacity, float loadFactor) {
map = new HashMap<>(initialCapacity, loadFactor);
}
/* 构建空集合,指定 容量大小,使用默认的 负载因子 0.75 */
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
/* 不对外开放的构造函数,指定 容量大小 与 负载因子,参数 dummy 只是为了重载构造,没有意义 */
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
1.2 HashSet 的属性定义
- 只有三个属性:版本(用于序列化),map(底层存储的key,value),PRESENT(用于作为map的值,与null区分)
static final long serialVersionUID = -5024744406713321676L;
/* set 的缓冲数据存储 */
private transient HashMap<E,Object> map;
/* PRESENT 空对象作为 hashmap 的value,不使用 null 是为了与获取key为null区分开 */
private static final Object PRESENT = new Object();
2 操作函数
2.1 add()
- 调用 HashMap 的 put 方法。
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
2.2 size()
- 返回 map 的size
public int size() {
return map.size();
}
2.3 isEmpty()
- 判断是否为空,根据 map.size == 0 返回结果
public boolean isEmpty() {
return map.isEmpty();
}
public boolean isEmpty() {
return size == 0;
}
2.4 contains()
- 是否包含某个元素
public boolean contains(Object o) {
return map.containsKey(o);
}
2.5 remove()
- map.remove(o) 返回的是删除元素的 value 值
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
2.6 clear()
- 调用的是 map.clear()
public void clear() {
map.clear();
}
2.7 iterator()
- 调用 map 的 key 遍历器
public Iterator<E> iterator() {
return map.keySet().iterator();
}
2.8 spliterator()
- 调用 map 的 key 分解迭代器
public Spliterator<E> spliterator() {
return new HashMap.KeySpliterator<E,Object>(map, 0, -1, 0, 0);
}
2.9 总结
- HashSet 实际上就是使用 HasMap 的 key 来完成的存储不重复元素。也就是说,想学好 HashSet,学会 HashMap 就可以了。
3. HashSet 线程安全吗?
- HashMap 线程不安全,HashMap 肯定也不安全。
import java.util.HashSet;
import java.util.concurrent.*;
public class ThreadSetTest {
public static void main(String[] args) throws InterruptedException {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(50, 100, 0L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>());
CountDownLatch countDownLatch = new CountDownLatch(10);
HashSet<Integer> hashSet = new HashSet<>();
for(int i = 1; i <= 10; i++) {
int finalI = i;
threadPoolExecutor.execute(() -> {
for(int j = 1; j <= 10; j++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
hashSet.add(finalI * 10 + j);
};
countDownLatch.countDown();
});
}
countDownLatch.await();
System.out.println("hashSet.size(): " + hashSet.size());
System.out.println("hashSet: ");
int num = 0;
for (Integer integer : hashSet) {
System.out.print(integer + "\t");
if(++num >= 10) {
num = 0;
System.out.println();
}
}
}
}
- size变小,元素个数变少,具体原因分析可看 HashMap 篇,这里不做赘述。
3.1 线程安全解决
- 使用 Collections.synchronizedSet()
package cn.cerish.container.collection.set;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadSafeResolveTest {
public static void main(String[] args) throws InterruptedException {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(50, 100, 0L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>());
Set<Integer> hashSet = Collections.synchronizedSet(new HashSet<Integer>());
CountDownLatch countDownLatch = new CountDownLatch(10);
for(int i = 1; i <= 10; i++) {
int finalI = i;
threadPoolExecutor.execute(() -> {
for(int j = 1; j <= 10; j++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
hashSet.add(finalI * 10 + j);
};
countDownLatch.countDown();
});
}
countDownLatch.await();
System.out.println("hashSet.size(): " + hashSet.size());
System.out.println("hashSet: ");
int num = 0;
for (Integer integer : hashSet) {
System.out.print(integer + "\t");
if(++num >= 10) {
num = 0;
System.out.println();
}
}
}
}