Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Finding an element in a map

 
Neelesh Bodas
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I understand correctly, the process of searching a key in a map is a two step process
a) use hashcode() to get the correct bucket
b) use equals() method to find the object.
[ K&B, page 566, Chapter 7]

Now my question is : Is this just for our own understanding, or is it the way the keys are searched ACTUALLY while using the get() method?

I wrote a sample code which tries to search for a key in a TreeMap. I added print statements to hashcode() and equals() methods but none of them got printed. Hence the question.

The code is presented below for reference

 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I understand correctly, the process of searching a key in a map is a two step process
a) use hashcode() to get the correct bucket
b) use equals() method to find the object.
[ K&B, page 566, Chapter 7]

Now my question is : Is this just for our own understanding, or is it the way the keys are searched ACTUALLY while using the get() method?


Well not always. bucket concept applies to hashing collections, HashMap etc.

If you know the key element, then you can find value by first checking the presence of key by containsKey(Object key) method of Map or you can get a set of Map.Entry which will give you all keys and values of the Map.

Naseem
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic