Which Map.Entry scenario returns map.entrySet to be NULL

I came across a piece of code that iterates over a map using its own set of records and only performs an action if entry! = Null

As far as I know, even if we do not enter anything on the map, it map.entrySetreturns an empty set, not null. Even if I put it {null,null}, then the record will be an [null=null]instance with these elements. But the instance will not be empty.

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 some basic questions:

  • In which scenario will the HashMap write be NULL?
  • Is the check even valid

I really believe if(entry != null)carefully and need to be removed. I just want to be sure.

+4
source share
3 answers

, , , , Maps. .

+4

. hashmap

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

,

+1

Validation can only be validated in order to create an instance of the map, to avoid NullPointerExceptionfurther references to the object.
If you think this is a warning, you must make sure that the Map was created in your constructor.

-1
source

All Articles