public V get(Object key) { if (key == null) return getForNullKey(); int hash = hash(key.hashCode()); for (Entry<K,V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) return e.value; } return null; } /** * Offloaded version of get() to look up null keys. Null keys map * to index 0. This null case is split out into separate methods * for the sake of performance in the two most commonly used * operations (get and put), but incorporated with conditionals in * others. */ private V getForNullKey() { for (Entry<K,V> e = table[0]; e != null; e = e.next) { if (e.key == null) return e.value; } return null; }
Map map = new HashMap(); map.put(null, "test"); // ... !
System.out.println(map.size()); // : 1 System.out.println(map.get(null)); // : test
When a new key-value pair is added, it calculates the key's hash code, based on which the basket number is calculated (the cell number of the array) into which the new item will fall.
map.put(0, "0"); System.out.println(map.size()); // : 2
Map map = new HashMap(); map.put(null, null); map.get(null); // null , , map.containsKey(null); // true: ,
Map map = new TreeMap(); map.put(null, "null"); // !
System.out.println(map.size()); // : 1 System.out.println(map.get(null)); // !! Exception in thread "main" java.lang.NullPointerException
Map map = new TreeMap(); map.put(null, "null"); // System.out.println(map.size()); // : 1 map.put(0, "0"); // !! Exception in thread "main" java.lang.NullPointerException
Map map = new TreeMap(); map.put(0, "0"); // map.put(1, 1); // System.out.println(map.size()); // : 2 map.put(null, "null"); // !! Exception in thread "main" java.lang.NullPointerException
Source: https://habr.com/ru/post/164027/