This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design 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
Pie
Posts: 20958
31
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