Map集合中get不存在的key值
阿新 • • 發佈:2019-01-08
先來看下面的程式碼:
Map<String, String> map = new HashMap<>();
String test = map.get("test");
System.out.println(test);
輸出結果:
null
從結果可以看出,HashMap集合中,獲取不存在的key時並不會報異常.
在Map的實現類HashMap中有這樣一段程式碼
public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; } /** * Implements Map.get and related methods * * @param hash hash for key * @param key the key * @return the node, or null if none */ 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; }
在get方法中並沒有向上丟擲異常,註釋也說明了返回節點或者null