One of the common programming task while using HashMap in Java is to check if a given key exists in the map or not. This is supposed to be easy, right? Yes, it is easy if you know your API well, all you need to is call the containsKey() method, it returns true if given key exists in HashMap, otherwise false; but I have seen many programmer's codes like we will see in this article, which prompted me to write this blog post.
if(map.get(key) != null){
System.out.println("key exits in Map");
}
This code is fragile, it will not work if you have added null values into HashMap, remember HashMap does allow null values. Many programers will test this code for some input and think that it's working fine, only to create a subtle bug in production. It's always better to use an API method if it can do the job, many greats have advised this. Joshua Bloch even included a chapter on his classic book Effective Java, a must-read book for any Java programmer.
Read more »
if(map.get(key) != null){
System.out.println("key exits in Map");
}
This code is fragile, it will not work if you have added null values into HashMap, remember HashMap does allow null values. Many programers will test this code for some input and think that it's working fine, only to create a subtle bug in production. It's always better to use an API method if it can do the job, many greats have advised this. Joshua Bloch even included a chapter on his classic book Effective Java, a must-read book for any Java programmer.
No comments:
Post a Comment