Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap null value issue

Tags:

java

What is the difference between both of result.

  1. When I've null value with key

  2. 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
like image 277
user3801322 Avatar asked Dec 10 '14 11:12

user3801322


People also ask

IS null value allowed in HashMap?

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.

How does HashMap handle null values?

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.

Can Java map have null value?

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.

Can we put null as key in HashMap?

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.


Video Answer


1 Answers

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.

like image 92
Eran Avatar answered Oct 03 '22 09:10

Eran