⬆️ ⬇️

Java job interview. Collections vs null

Hello!



In java topic interview. The collections detail the issue of working with Set & Map in Java. But I still have a couple of favorite questions from this area:



  1. Can null be used as a key in a Map?
  2. Can a set be null ?


hint (HashMap.java)
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; } 




It is supposed that the inquisitive reader will independently reflect on the answers and then compare them with mine. The most impatient can immediately proceed under the cat.



1. Can null be used as a key in a Map?


Hashmap


 Map map = new HashMap(); map.put(null, "test"); //   ...  ! 


We look that inside

 System.out.println(map.size()); // : 1 System.out.println(map.get(null)); // : test 


What is going on? Quote from the source:

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.


That is, it turns out that hash-code from null is calculated ... hmmm. But how is it calculated without an object, without hashCode ()? My answer is I don’t know, but the debugger shows that for null hash = 0. Apparently somewhere there is a separate check.

')

Then everything without surprises, another object with hash = 0 falls into the same “basket”.

 map.put(0, "0"); System.out.println(map.size()); // : 2 


Answer # 1: HashMap operates with a null key without any problems. Its hash is always 0

for a particularly exotic map.put case (null, null)
 Map map = new HashMap(); map.put(null, null); map.get(null); //  null  ,      ,       map.containsKey(null); //  true:      ,     


thank you Vanger13





Treemap


 Map map = new TreeMap(); map.put(null, "null"); //  ! 


But it should be!
javadoc requires NPE

thanks vkolotov



We look that inside

 System.out.println(map.size()); // : 1 System.out.println(map.get(null)); // !! Exception in thread "main" java.lang.NullPointerException 


But it all started well! Put the put, it lies there (size = 1), but we can not get it back. Well, ok, let's say we don't need to get anything at all. And we just want to put, so strange we are. We try.

 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 


Single Mapa, some. Or not? Add dramas, change the order of insertion

 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 


What kind of daisy it turns out, null, it works, it does not work? And it turns out that's what. When we add the null key to an empty tree, it gets into root. And root, comrades, he is also in root in Africa, he is more equal than all the others, for him there is no call to compareTo () and null quietly takes its place in the root of the tree. And if the tree is not empty, attempts are made to compare with the existing content, and we get a “legitimate” NPE. There are no special conditions for null here.



Answer # 2: You can put a single null key in an empty TreeMap, all other operations (except size () and clear (), by the way) do not work after that. You cannot put a null key in a non-empty TreeMap due to the obligatory call of compareTo ().



2. Can Set be null?


The answer to this question repeats the previous ones, given that the Set is actually implemented on the basis of the Map. HashSet works with a bang, TreeSet - only for the first element.



Thanks for attention.



Useful links:

Java job interview. Collections by sphinks

Data structures: binary trees. Part 1 by winger

Data structures: binary trees. Part 2: an overview of balanced trees by winger

Data structures in pictures. HashMap by tarzan82

Source: https://habr.com/ru/post/164027/



All Articles