Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Rajasekar Elango
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Paul Clapham
Sheriff
Posts: 21316
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
get() would also be ok with HashTable, but it may be good practice to use containsKey() instead. (for readability)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic