总结 HashSet:
HashSet的底层是HashMap
并且HashSet中的set相当于在HashMap的key,而value则是new Object出来的常量
扩容条件则是按照HashMap的扩容规则进扩容
源码
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable {
@java.io.Serial
static final long serialVersionUID = -5024744406713321676L; // 序列化版本号
private transient HashMap<E,Object> map; // 底层采用HashMap进行存储
private static final Object PRESENT = new Object(); // 作为HashMap中的value常量,而key则是真正set要存的数据
public HashSet() {
map = new HashMap<>(); // 直接创建一个HashMap
}
public HashSet(Collection<? extends E> c) { // 传入一个集合
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16)); // 创建一个带初始容量的HashMap
addAll(c); // 将集合c中的元素添加进map中
}
public HashSet(int initialCapacity, float loadFactor) {
map = new HashMap<>(initialCapacity, loadFactor); // 带初始容量和扩容因子的map
}
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity); // 带初始容量的map
}
HashSet(int initialCapacity, float loadFactor, boolean dummy) { // 只在内部使用的构造方法,创建一个LinkedHashMap
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
public Iterator<E> iterator() {
return map.keySet().iterator();
}
public int size() {
return map.size(); //返回map存有多少个元素
}
public boolean isEmpty() {
return map.isEmpty(); // 判断map是否为空
}
public boolean contains(Object o) {
return map.containsKey(o); // 判断o是否在map中
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;// 添加元素,将数据作为key
}
public boolean remove(Object o) {
return map.remove(o)==PRESENT; // 移除元素
}
public void clear() {
map.clear(); // 清空map
}
@SuppressWarnings("unchecked")
public Object clone() {
try {
HashSet<E> newSet = (HashSet<E>) super.clone(); // 拷贝HashSet
newSet.map = (HashMap<E, Object>) map.clone(); // 拷贝map将map赋值给上面拷贝的HashSet中
return newSet; // 返回set
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
// 序列化
@java.io.Serial
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
s.defaultWriteObject();
s.writeInt(map.capacity());
s.writeFloat(map.loadFactor());
s.writeInt(map.size());
for (E e : map.keySet())
s.writeObject(e);
}
// 反序列化
@java.io.Serial
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);
SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Map.Entry[].class, HashMap.tableSizeFor(capacity));
map = (((HashSet<?>)this) instanceof LinkedHashSet ? new LinkedHashMap<>(capacity, loadFactor) : new HashMap<>(capacity, loadFactor));
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<>(map, 0, -1, 0, 0); // 获取key的迭代器
}
@Override
public Object[] toArray() {
return map.keysToArray(new Object[map.size()]); // map的key转换为数组
}
@Override
public <T> T[] toArray(T[] a) {
return map.keysToArray(map.prepareArray(a)); // 带泛型的转换key为数组
}
}