File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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


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: 18570
    
    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: 14688
    
  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
 
GeeCON Prague 2014
 
subject: HashMap.get() != null vs HashMap.containsKey()