• Post Reply Bookmark Topic Watch Topic
  • New Topic

Under what scenario entry returned by map.entrySet is NULL ?  RSS feed

 
Sunni srivastav
Greenhorn
Posts: 24
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 this method returns an empty set and not a null set.
Even if I put {null,null} then the entry will be [null,null] employing an instance of set with these elements.



I have below question:
1. Under what scenario an entry in HashMap will it be NULL?
2. Is the check even valid ?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This never happens; the person who wrote that code was mistaken, or overly concerned about NullPointerExceptions.

The null check is redundant and can be removed without any change in functionality.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's possible in a HashMap for the key or value to be null. So doing this may make sense in some circumstances:

But as Jesper says, the Entry itself will never be null.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!