Ответ 1
Если вы посмотрите на реализацию HashMap
, конструктор выглядит так:
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();
}
И 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() {
}
Итак, initialCapacity
фактически не используется для создания массива. Где он используется? Посмотрите на метод put()
.
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
// hidden
}
При выполнении put массив фактически создается. Я не показывал inflateTable()
, но он выполняет некоторую математику и инициализирует массив.