wood burning stoves 2.0*
The moose likes Java in General and the fly likes HashMap.get() != null vs HashMap.containsKey() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "HashMap.get() != null vs HashMap.containsKey()" Watch "HashMap.get() != null vs HashMap.containsKey()" New topic
Author

HashMap.get() != null vs HashMap.containsKey()

Rajasekar Elango
Ranch Hand

Joined: Sep 13, 2004
Posts: 105
Guys,

I want to retrive value of a key in hash map and throw exception if key not found, which one would be better..


OR


I am feeling that second approach is cleaner but little expensive in performance.

What do you guys think..?

Regards,
E. Rajasekar.


SCJP 1.4
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

Only the second one actually works, so there is no point in considering the first one. The documentation for the "get" method says:

"A return value of null does not necessarily indicate that the map contains no mapping for the key; it is also possible that the map explicitly maps the key to null. The containsKey method may be used to distinguish these two cases."
Rajasekar Elango
Ranch Hand

Joined: Sep 13, 2004
Posts: 105
Hi,

Thanks for point me to HashMap documentation.. I forgot that hash map allows null keys. But what if it is hash table..?

Thanks,
E. Rajasekar.
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

get() would also be ok with HashTable, but it may be good practice to use containsKey() instead. (for readability)


[My Blog]
All roads lead to JavaRanch
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: HashMap.get() != null vs HashMap.containsKey()