简介
内部基于CopyOnWriteArrayList实现的Set集合
类图
属性
// 内部依赖CopyOnWriteArrayList实现
private final CopyOnWriteArrayList<E> al;
构造方法
// 内部使用CopyOnWriteArrayList存储数据
public CopyOnWriteArraySet() {
al = new CopyOnWriteArrayList<E>();
}
public CopyOnWriteArraySet(Collection<? extends E> c) {
if (c.getClass() == CopyOnWriteArraySet.class) {
@SuppressWarnings("unchecked") CopyOnWriteArraySet<E> cc =
(CopyOnWriteArraySet<E>)c;
al = new CopyOnWriteArrayList<E>(cc.al);
}
else {
al = new CopyOnWriteArrayList<E>();
al.addAllAbsent(c);
}
}
如何保证不重复
// 调用List的当不存在时添加方法
public boolean add(E e) {
return al.addIfAbsent(e);
}
// 不存在才会添加
public boolean addIfAbsent(E e) {
Object[] snapshot = getArray();
return indexOf(e, snapshot, 0, snapshot.length) >= 0 ? false :
addIfAbsent(e, snapshot);
}
private boolean addIfAbsent(E e, Object[] snapshot) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] current = getArray();
int len = current.length;
if (snapshot != current) {
// 说明在这之前已经被修改过了
int common = Math.min(snapshot.length, len);
// 判断元素是否存在于当前数组中,如果存在直接返回false;
// 这里巧妙地思路:判断两个数组相等 1长度相等 2数组每一位相等 不需要进行双重循环
for (int i = 0; i < common; i++)
if (current[i] != snapshot[i] && eq(e, current[i]))
return false;
if (indexOf(e, current, common, len) >= 0)
return false;
}
// 添加并修改
Object[] newElements = Arrays.copyOf(current, len + 1);
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}