this.loadFactor = loadFactor;
//返回2的幂次方
this.threshold = tableSizeFor(initialCapacity);
}
复制代码
对于上面的构造器,我们需要注意的是`this.threshold = tableSizeFor(initialCapacity);`这边的 threshold 为 2的幂次方,而不是`capacity * load factor`,当然此处并非是错误,因为此时 table 并没有真正的被初始化,初始化动作被延迟到了`putVal()`当中,所以 threshold 会被重新计算。
/**
-
根据指定的容量以及默认负载因子(0.75)初始化一个空的 HashMap 实例
-
如果 initCapacity是负数,那么将抛出 IllegalArgumentException
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
- 根据默认的容量和负载因子初始化一个空的 HashMap 实例
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
/**
-
Constructs a new HashMap with the same mappings as the
-
specified Map. The HashMap is created with
-
default load factor (0.75) and an initial capacity sufficient to
-
hold the mappings in the specified Map.
-
@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.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
复制代码
### 查询
/**
-
返回指定 key 所对应的 value 值,当不存在指定的 key 时,返回 null。
-
当返回 null 的时候并不表明哈希表中不存在这种关系的映射,有可能对于指定的 key,其对应的值就是 null。
-
因此可以通过 containsKey 来区分这两种情况。
*/
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
-
1.首先通过 key 的哈希值找到其所在的哈希桶
-
2.对于 key 所在的哈希