*/
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 所在的哈希桶只有一个元素,此时就是 key 对应的节点,
-
3.对于 key 所在的哈希桶超过一个节点,此时分两种情况:
-
如果这是一个 TreeNode,表明通过红黑树存储,在红黑树中查找
-
如果不是一个 TreeNode,表明通过链表存储(链地址法),在链表中查找
-
4.查找不到相应的 key,返回 null
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
复制代码
存储
/**
- 在映射中,将指定的键与指定的值相关联。如