What is the difference between both of result.
When I've null value with key
When key itself is not exist
In above both condition result is null. So how can i identify my key value
Map map = new HashMap();
map.put(1,null);
System.out.println(map.get(1));
System.out.println(map.get(2));
Answer:
null
null
HashMap allows one null key and multiple null values whereas Hashtable doesn't allow any null key or value. HashMap is generally preferred over HashTable if thread synchronization is not needed.
HashMap puts null key in bucket 0 and maps null as key to passed value. HashMap does it by linked list data structure. HashMap uses linked list data structure internally. In Entry class the K is set to null and value mapped to value passed in put method.
HashMap: HashMap implements all of the Map operations and allows null values and one null key. HashMap does not maintain an order of its key-value elements. Therefore, consider to use a HashMap when order does not matter and nulls are acceptable.
HashMap is similar to HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values.
While get
returns the same result for null
value and non-existing key, containsKey
doesn't:
map.containsKey(1)
would return true
.
map.containsKey(2)
would return false
.
In addition, if you iterate over the keys of the Map
(using keySet()
), 1
will be there and 2
won't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With