Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under what scenario Map.Entry returned by map.entrySet will be NULL

I came across a code snippet which iterates over a map using its entry set and performs some action only if entry != null

As far as I know even if we don't enter anything in map map.entrySet returns an empty set and not null. Even if I put {null,null} then the entry will be [null=null] i.e an instance with these elements. But the instance won't be null.

Map<String, String> map = new HashMap<String, String>();
        map.put(null, null);
        map.put(string1, string1);
        for(Map.Entry<String, String> entry : map.entrySet()){
            if(entry != null){
                                  //do something
            }

        }

I have below basic questions:

  1. Under what scenario an entry in HashMap will be NULL?
  2. Is the check even valid

I strongly believe if(entry != null) over caution and it should be removed.I just want to be sure.

like image 897
Abhinav Avatar asked May 18 '15 06:05

Abhinav


People also ask

Can map entrySet return null?

entrySet returns an empty set and not null .

What does HashMap entrySet return?

The Java HashMap entrySet() returns a set view of all the mappings (entries) present in the hashmap. Here, hashmap is an object of the HashMap class.

How do you check if a map is null?

isEmpty and MapUtils. isEmpty() methods which respectively check if a collection or a map is empty or null (i.e. they are "null-safe").

Can a map value be null?

Yes, null is always a valid map key for any type of map key (including primitives, sobjects, and user-defined objects).


2 Answers

An iterator could return nulls for collections that support null values, but as you yourself showed this isn't possible for Maps. The check is redundant and misleading.

like image 176
Kayaman Avatar answered Oct 24 '22 19:10

Kayaman


The scenario is invalid. This is code from the hashmap implementation

private Set<Map.Entry<K,V>> entrySet0() {
    Set<Map.Entry<K,V>> es = entrySet;
    return es != null ? es : (entrySet = new EntrySet());
}

So, you should not get a null value

like image 23
bobK Avatar answered Oct 24 '22 20:10

bobK