环境和版本

  • Mac M1
  • IDEA 2021
  • Zulu Open JDK

    简介

  • HashSet:Set集合,其本质存储的是HashMap的Key。

  • Set内的元素不重复且无序
  • 因为之前分析过HashMap的源码,此处做简要论述即可

    属性

    image.png ```java // 底层就是 Map private transient HashMap map;

// Value private static final Object PRESENT = new Object();

  1. <a name="SDz2E"></a>
  2. # 构造函数
  3. ```java
  4. public HashSet() {
  5. map = new HashMap<>();
  6. }
  7. public HashSet(Collection<? extends E> c) {
  8. map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
  9. addAll(c);
  10. }
  11. public HashSet(int initialCapacity, float loadFactor) {
  12. map = new HashMap<>(initialCapacity, loadFactor);
  13. }
  14. public HashSet(int initialCapacity) {
  15. map = new HashMap<>(initialCapacity);
  16. }
  17. // 这个是给LinkedHashSet用的
  18. HashSet(int initialCapacity, float loadFactor, boolean dummy) {
  19. map = new LinkedHashMap<>(initialCapacity, loadFactor);
  20. }

序列化和反序列化

private void writeObject(java.io.ObjectOutputStream s)
    throws java.io.IOException {
    // Write out any hidden serialization magic
    s.defaultWriteObject();

    // Write out HashMap capacity and load factor
    s.writeInt(map.capacity());
    s.writeFloat(map.loadFactor());

    // Write out size
    s.writeInt(map.size());

    // Write out all elements in the proper order.
    for (E e : map.keySet())
        s.writeObject(e);
}


private void readObject(java.io.ObjectInputStream s)
    throws java.io.IOException, ClassNotFoundException {
    // Read in any hidden serialization magic
    s.defaultReadObject();

    // Read capacity and verify non-negative.
    int capacity = s.readInt();
    if (capacity < 0) {
        throw new InvalidObjectException("Illegal capacity: " +
                                         capacity);
    }

    // Read load factor and verify positive and non NaN.
    float loadFactor = s.readFloat();
    if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
        throw new InvalidObjectException("Illegal load factor: " +
                                         loadFactor);
    }

    // Read size and verify non-negative.
    int size = s.readInt();
    if (size < 0) {
        throw new InvalidObjectException("Illegal size: " +
                                         size);
    }
    // Set the capacity according to the size and load factor ensuring that
    // the HashMap is at least 25% full but clamping to maximum capacity.
    capacity = (int) Math.min(size * Math.min(1 / loadFactor, 4.0f),
                              HashMap.MAXIMUM_CAPACITY);

    // Constructing the backing map will lazily create an array when the first element is
    // added, so check it before construction. Call HashMap.tableSizeFor to compute the
    // actual allocation size. Check Map.Entry[].class since it's the nearest public type to
    // what is actually created.

    SharedSecrets.getJavaOISAccess()
        .checkArray(s, Map.Entry[].class, HashMap.tableSizeFor(capacity));

    // Create backing HashMap
    map = (((HashSet<?>)this) instanceof LinkedHashSet ?
           new LinkedHashMap<E,Object>(capacity, loadFactor) :
           new HashMap<E,Object>(capacity, loadFactor));

    // Read in all elements in the proper order.
    for (int i=0; i<size; i++) {
        @SuppressWarnings("unchecked")
        E e = (E) s.readObject();
        map.put(e, PRESENT);
    }
}

其他方法

  • 其他方法参见HashMap,HashMap懂了之后,HashSet看毛线