HashMap 構造函數

HashMap總共提供了三個構造函數函數

1  /**
2      * Constructs an empty <tt>HashMap</tt> with the default initial capacity
3      * (16) and the default load factor (0.75).
4      */
5     public HashMap() {
6         this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
7     }

解讀:這是無參構造函數,構造了一個初始容量16和負載因子爲0.75的HashMap實例。
      負載因子介紹請參考本人博客:"HashMap負載因子"this

 

 1 /**
 2      * Constructs an empty <tt>HashMap</tt> with the specified initial
 3      * capacity and the default load factor (0.75).
 4      *
 5      * @param  initialCapacity the initial capacity.
 6      * @throws IllegalArgumentException if the initial capacity is negative.
 7      */
 8     public HashMap(int initialCapacity) {
 9         this(initialCapacity, DEFAULT_LOAD_FACTOR);
10     }

解讀:構造一個指定初始容量的HashMap實例,此時負載因子仍是0.75.spa

 1     /**
 2      * Constructs an empty <tt>HashMap</tt> with the specified initial
 3      * capacity and load factor.
 4      *
 5      * @param  initialCapacity the initial capacity
 6      * @param  loadFactor      the load factor
 7      * @throws IllegalArgumentException if the initial capacity is negative
 8      *         or the load factor is nonpositive
 9      */
10     public HashMap(int initialCapacity, float loadFactor) {
11         if (initialCapacity < 0)
12             throw new IllegalArgumentException("Illegal initial capacity: " +
13                                                initialCapacity);
14         if (initialCapacity > MAXIMUM_CAPACITY)
15             initialCapacity = MAXIMUM_CAPACITY;
16         if (loadFactor <= 0 || Float.isNaN(loadFactor))
17             throw new IllegalArgumentException("Illegal load factor: " +
18                                                loadFactor);
19         this.loadFactor = loadFactor;
20         this.threshold = tableSizeFor(initialCapacity);
21     }

解讀:指定初始容量和負載因子構造一個HashMap實例.code

相關文章
相關標籤/搜索