Java集合系列-HashSet

唯一浩哥發表於2020-11-11

原創文章,轉載請標註出處:https://www.cnblogs.com/V1haoge/p/10755431.html

一、概述

HashSet是基於雜湊實現的set集合,其實它底層是一個value固定的HashMap。
HashMap是無序儲存的,所以HashSet也一樣是無序的,而且HashSet允許null值,但只能擁有一個null值,即不允許儲存相同的元素。

二、常量變數

public class HashSet<E> extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable
{
    //...
    private transient HashMap<E,Object> map;
    private static final Object PRESENT = new Object();
    //...
}

上面的map即為HashSet底層的HashMap,針對HashSet的操作,全部轉交給這個map來完成。
上面的PRESENT即為底層HashMap中鍵值對的值的固定值。因為在HashSet中只關注鍵。

三、構造器

public class HashSet<E> extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable{
    //...
    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);
    }    
    //...
}

很明顯,所有的HashSet的構造器最終都在建立底層的HashMap。
最後一個構造器建立了一個LinkedHashMap例項,其實它也是一個HashMap,因為它繼承自HashMap,是對HashMap的一個功能擴充套件集合,它支援多種順序的遍歷(插入順序和訪問順序)。

四、操作

public class HashSet<E> extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable{
    //...
    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) {
        return map.containsKey(o);
    }
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
    public boolean remove(Object o) {
        return map.remove(o)==PRESENT;
    }
    public void clear() {
        map.clear();
    }
    //...
}

上面的所有基礎操作,全部已開HashMap的對應方法來完成。

五、序列化操作

5.1 序列化

HashSet例項的序列化執行時,並不會序列化map屬性,因為其被transient關鍵字所修飾。參照原始碼:

// 在執行序列化操作的時候會執行這個writeObject方法
public class HashSet<E> extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable
{
    //...
    private transient HashMap<E,Object> map;
    private static final Object PRESENT = new Object();
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        // Write out any hidden serialization magic
        // 用於將物件中的非static和非transient的欄位值寫入流中
        s.defaultWriteObject();
        // Write out HashMap capacity and load factor
        // 將底層HashMap的當前容量和載入因子寫入流中
        s.writeInt(map.capacity());
        s.writeFloat(map.loadFactor());
        // Write out size
        // 將底層HashMap的當前元素數量size寫入流中
        s.writeInt(map.size());
        // Write out all elements in the proper order.
        // 最後將所有的元素寫入流中
        for (E e : map.keySet())
            s.writeObject(e);
    }
    //...
}

5.2 反序列化

// 在執行反序列化操作的時候會執行這個readObject方法
public class HashSet<E> extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable
{
    //...
    private transient HashMap<E,Object> map;
    private static final Object PRESENT = new Object();
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in any hidden serialization magic
        // 讀取流中對應的當前類的非static和非transient的值
        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
        // 建立底層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.
        // 讀取流中儲存的元素,並將其逐個新增到新建立的HashMap例項中
        for (int i=0; i<size; i++) {
            @SuppressWarnings("unchecked")
                E e = (E) s.readObject();
            map.put(e, PRESENT);
        }
    }
    //...
}

六、總結

HashSet就是依靠HashMap實現的。

相關文章