javadictionaryhashmapentryset

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.


Solution

  • 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.