HashMap指定初始容量的構造函數-基於源碼分析

今日主題是源碼分析之HashMap指定初始容量的構造函數(以下都是基於jdk1.8)。

HashMap可以指定初始容量大小的構造函數有兩個:

    /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

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

	/**
     * The next size value at which to resize (capacity * load factor).
     *
     * @serial
     */
    // (The javadoc description is true upon serialization.
    // Additionally, if the table array has not been allocated, this
    // field holds the initial array capacity, or zero signifying
    // DEFAULT_INITIAL_CAPACITY.)
    int threshold;

    /**
     * The load factor for the hash table.
     *
     * @serial
     */
    final float loadFactor;
    
    /**
     * 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;
        this.threshold = tableSizeFor(initialCapacity);
    }
    
     /**
     * 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);
    }
    

看第一個構造函數即可,因爲第二個也是通過第一個來實現的,只是加載因子是默認值0.75 。

接下來看tableSizeFor方法:

    /**
     * Returns a power of two size for the given target capacity.
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
    

通過註釋可以看到,我們傳進來的初始容量值,經過一系列的無符號右移運算和位的或運算,最終給我們返回最接近我們指定的初始容量值的2的冪次方。

這裏不需要考慮指定初始容量值爲負數的情況,因爲在構造函數中已經進行了判斷。如果爲負數,則程序將拋出異常。

爲什麼要先進行一步減1的操作呢?這是因爲當我們指定初始容量正好是2的冪次方時,比如8,經過上述一系列的運算,最終會返回16,然而最接近於指定值的2的冪次方就是它本身。爲了解決這一問題,程序首先執行了減1操作。

tableSizeFor方法的返回值賦值給了變量threshold,如果現在你還看不出來這個變量的作用也沒關係,在接下來的博客中你將繼續看到它的身影~

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