源碼之HashSet

構造函數

    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);
    }

   /**
     * Constructs a new, empty linked hash set.  (This package private
     * constructor is only used by LinkedHashSet.) The backing
     * HashMap instance is a LinkedHashMap with the specified initial
     * capacity and the specified load factor.
     *
     * @param      initialCapacity   the initial capacity of the hash map
     * @param      loadFactor        the load factor of the hash map
     * @param      dummy             ignored (distinguishes this
     *             constructor from other int, float constructor.)
     * @throws     IllegalArgumentException if the initial capacity is less
     *             than zero, or if the load factor is nonpositive
     */
    HashSet(int initialCapacity, float loadFactor, boolean dummy) {
        map = new LinkedHashMap<>(initialCapacity, loadFactor);
    }

分析:
HashSet底層是HashMap實現的,你看最後一個構造函數就會很奇怪,這dummy的參數幹啥的 ,啥也沒用。不過這個看說明就知道了,只是爲了實現構造函數的重載,跟其他區別開來的(如果不明白有必要看下重載內容)。

add方法

    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }

分析:
這就很簡單可以知道了,就是將E作爲HashMap的key,所有的key都指向PRESENT對象,因爲我們都知道,key是不允許重複的,而value可以。

另外這裏沒有HashMap的那種get方法去獲取key的,只能通過迭代器去便利裏面的值。

總結:
1.它不是線程安全的
2.它是由HashMap實現的
3.通過map.put(key,PRESENT)方式把所有key指向同一個對象
4.訪問只能通過迭代器訪問。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章