【Hashmap1.7】構造方法

一、認識構造方法

1、public HashMap()

解釋:初始化一個空的hashmap,擁有16的容量和0.75的負載因子。

    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }

    /**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16


    /**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

 

2、public HashMap(int initialCapacity)

有指定容量(initialCapacity)的hashmap

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and the default load factor (0.75).
     *
     * @param  initialCapacity the initial capacity.
     * @throws IllegalArgumentException if the initial capacity is negative.
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

3、public HashMap(int initialCapacity, float loadFactor)

指定容量和負載因子的hashmap。前兩個構造函數都是調用這個函數完成構造的,所以這個纔是重點

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);

        this.loadFactor = loadFactor;
        threshold = initialCapacity;
        init();
    }

4、public HashMap(Map<? extends K, ? extends V> m)

構造一個與指定 Map 具有相同映射的 HashMap,其初始容量依賴於指定Map的大小,負載因子是 0.75

    /**
     * Constructs a new <tt>HashMap</tt> with the same mappings as the
     * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
     * default load factor (0.75) and an initial capacity sufficient to
     * hold the mappings in the specified <tt>Map</tt>.
     *
     * @param   m the map whose mappings are to be placed in this map
     * @throws  NullPointerException if the specified map is null
     */
    public HashMap(Map<? extends K, ? extends V> m) {
        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
                      DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
        inflateTable(threshold);

        putAllForCreate(m);
    }

二、瞭解構造函數

前兩個構造函數的工作都是調用第三個完成的,所以我們直接從第三個開始看起。

    public HashMap(int initialCapacity, float loadFactor) {
        //1.1 校驗initialCapacity,如果小於0,直接拋出異常
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        //1.2 如果大於MAXIMUM_CAPACITY(2的30次方),如果大於最大容量,則創建最大容量
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        //1.3 校驗負載因子是大於0的數字值
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        //2 賦值,threshold 閾值/臨界值此時爲容量大小,後面第一次put時由inflateTable(int toSize)方法計算設置
        this.loadFactor = loadFactor;
        threshold = initialCapacity;
        init();
    }

    init();沒有明白這個方法怎麼什麼都沒有,根據翻譯大概意思就是要給它的子類用
    /**
     * Initialization hook for subclasses. This method is called
     * in all constructors and pseudo-constructors (clone, readObject)
     * after HashMap has been initialized but before any entries have
     * been inserted.  (In the absence of this method, readObject would
     * require explicit knowledge of subclasses.)
     */
    void init() {
    }

第四個構造函數

   

    public HashMap(Map<? extends K, ? extends V> m) {
        //1 調用第三個構造函數,容量大小在這裏做了一個比較
        //比較規則:m.size() / 0.75) + 1和16的最大值
        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
                      DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
        //2 擴容,threshold在調用構造函數時,初始化爲容量:threshold = initialCapacity;
        inflateTable(threshold);
        //3 放數據
        putAllForCreate(m);
    }

    /**
     * Inflates the table.
     */
    private void inflateTable(int toSize) {
        //找到一個2的次方的一個大於toSize的整數,作爲容量
        // Find a power of 2 >= toSize
        int capacity = roundUpToPowerOf2(toSize);
        //計算擴容的臨界值
        threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
        //創建一個容量爲capacity的table
        table = new Entry[capacity];
        //創建樹
        initHashSeedAsNeeded(capacity);
    }

    //
    private static int roundUpToPowerOf2(int number) {
        // assert number >= 0 : "number must be non-negative";
        return number >= MAXIMUM_CAPACITY
                ? MAXIMUM_CAPACITY
                : (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1;
    }

    /**
     * Initialize the hashing mask value. We defer initialization until we
     * really need it.
     */
    final boolean initHashSeedAsNeeded(int capacity) {
        boolean currentAltHashing = hashSeed != 0;
        boolean useAltHashing = sun.misc.VM.isBooted() &&
                (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
        boolean switching = currentAltHashing ^ useAltHashing;
        if (switching) {
            hashSeed = useAltHashing
                ? sun.misc.Hashing.randomHashSeed(this)
                : 0;
        }
        return switching;
    }

 

 

 

 

 

 

 

 

 

 

 

發佈了71 篇原創文章 · 獲贊 15 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章