Thursday, June 13, 2013

Java: Storing null key in HashMap

HashMap is useful in searching exact data in short time.
HashMap allows only one null key. Let's see how it stores null key internally.

If key is null, HashMap allows putting single value against null key. 
If you are trying to add another value against null key, it returns existing value for null key and stores new value against null key.
Internally HashMap maintains array of Entry class(internal class of HashMap which is used to store data) which is also called as Bucket.
Entry class contains key, value, nextElement, hash-value variables.

Data with null key is stored at Bucket location 0(array index 0 of Entry array). Hash value is also zero for null key.

Example:
HashMap h = new HashMap();  You can also use HashMap instead of HashMap.
h.put(null, "A");         -- Value "A" is stored against null key
h.put(null, "B");         -- Value "B" is stored against null key and old value "A" is returned as return type of put function is V i.e. value object
h.put(null, "C");         -- Value "C" is stored against null key and old value "B" is returned 



No comments: