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:
I strongly believe if(entry != null)
over caution and it should be removed.I just want to be sure.
entrySet returns an empty set and not null .
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.
isEmpty and MapUtils. isEmpty() methods which respectively check if a collection or a map is empty or null (i.e. they are "null-safe").
Yes, null is always a valid map key for any type of map key (including primitives, sobjects, and user-defined objects).
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.
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
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