HashSet的源码非常简单,它就是借用HashMap来实现相应的功能。
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
可以看出它继承自Ab stractSet抽样类,实现了Set接口,Cloneable可克隆接口,Serializable序列化接口。
一. Set接口
public interface Set<E> extends Collection<E> {
// 添加元素
boolean add(E e);
boolean addAll(Collection<? extends E> c);
// 删除元素
boolean remove(Object o);
boolean removeAll(Collection<?> c);
boolean retainAll(Collection<?> c);
void clear();
// 查询元素
// 是否包含某些元素
boolean contains(Object o);
boolean containsAll(Collection<?> c);
Iterator<E> iterator();
int size();
boolean isEmpty();
Object[] toArray();
<T> T[] toArray(T[] a);
boolean equals(Object o);
int hashCode();
@Override
default Spliterator<E> spliterator() {
return Spliterators.spliterator(this, Spliterator.DISTINCT);
}
}
继承自Collection接口,没有添加任何新的方法。
二. AbstractSet抽样类
public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {
protected AbstractSet() {
}
// 重写了equals方法。
public boolean equals(Object o) {
// 如果相等,就表示是同一个对象,返回true
if (o == this)
return true;
// 如果o不是Set集合子类,返回false
if (!(o instanceof Set))
return false;
Collection<?> c = (Collection<?>) o;
// 如果集合中元素个数不相同,返回false
if (c.size() != size())
return false;
try {
// 完全包含c集合,返回true
return containsAll(c);
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
}
public int hashCode() {
int h = 0;
// 得到迭代器
Iterator<E> i = iterator();
// 遍历所有元素,将它们的hashCode值累加,并返回
while (i.hasNext()) {
E obj = i.next();
if (obj != null)
h += obj.hashCode();
}
return h;
}
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
// 如果本集合元素个数大于集合c的元素个数
if (size() > c.size()) {
// 遍历集合c中每个元素,调用remove方法从本集合中删除该元素
for (Iterator<?> i = c.iterator(); i.hasNext(); )
modified |= remove(i.next());
} else {
// 通过迭代器,遍历本集合中所有元素
for (Iterator<?> i = iterator(); i.hasNext(); ) {
// 如果集合c中包含这个元素,那么就调用迭代器remove方法,删除这个元素
if (c.contains(i.next())) {
i.remove();
modified = true;
}
}
}
return modified;
}
}
继承自AbstractCollection抽样类,并且重写equals、hashCode和removeAll三个方法。
HashSet类
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
{
static final long serialVersionUID = -5024744406713321676L;
// 内部保存一个HashMap对象,通过它来实现对应功能
private transient HashMap<E,Object> map;
// 用于存放入HashMap中键值对元素的value值
private static final Object PRESENT = new Object();
// HashSet的构造函数都是调用HashMap对应的构造函数
public HashSet() {
map = new HashMap<>();
}
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);
}
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
// 返回map.keySet()的迭代器
public Iterator<E> iterator() {
return map.keySet().iterator();
}
public int size() {
return map.size();
}
public boolean isEmpty() {
return map.isEmpty();
}
public boolean contains(Object o) {
// map中是否包含对应的key值
return map.containsKey(o);
}
public boolean add(E e) {
// 向map中添加键值对,key值是e,value值是PRESENT
return map.put(e, PRESENT)==null;
}
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
public void clear() {
map.clear();
}
@SuppressWarnings("unchecked")
public Object clone() {
try {
HashSet<E> newSet = (HashSet<E>) super.clone();
newSet.map = (HashMap<E, Object>) map.clone();
return newSet;
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
// 序列化
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
s.defaultWriteObject();
// 写入map的阈值和负载因子
s.writeInt(map.capacity());
s.writeFloat(map.loadFactor());
// 写入map中元素个数
s.writeInt(map.size());
// 写入所有的key值
for (E e : map.keySet())
s.writeObject(e);
}
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
// 读取阈值
int capacity = s.readInt();
if (capacity < 0) {
throw new InvalidObjectException("Illegal capacity: " +
capacity);
}
// 读取负载因子
float loadFactor = s.readFloat();
if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
throw new InvalidObjectException("Illegal load factor: " +
loadFactor);
}
// 读取元素个数
int size = s.readInt();
if (size < 0) {
throw new InvalidObjectException("Illegal size: " +
size);
}
// 重新计算阈值
capacity = (int) Math.min(size * Math.min(1 / loadFactor, 4.0f),
HashMap.MAXIMUM_CAPACITY);
// 创建HashMap集合
map = (((HashSet<?>)this) instanceof LinkedHashSet ?
new LinkedHashMap<E,Object>(capacity, loadFactor) :
new HashMap<E,Object>(capacity, loadFactor));
// 读取所有的键值key,并将它存入map集合中,value值是PRESENT
for (int i=0; i<size; i++) {
@SuppressWarnings("unchecked")
E e = (E) s.readObject();
map.put(e, PRESENT);
}
}
public Spliterator<E> spliterator() {
return new HashMap.KeySpliterator<E,Object>(map, 0, -1, 0, 0);
}
}
网友评论