File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "HashMap.get() != null vs HashMap.containsKey()" Watch "HashMap.get() != null vs HashMap.containsKey()" New topic

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

Rajasekar Elango
Ranch Hand

Joined: Sep 13, 2004
Posts: 105

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


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

What do you guys think..?

E. Rajasekar.

SCJP 1.4
Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

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

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

E. Rajasekar.
Christophe Verré

Joined: Nov 24, 2005
Posts: 14688

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
I agree. Here's the link:
subject: HashMap.get() != null vs HashMap.containsKey()
It's not a secret anymore!