This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Finding an element in a map Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Finding an element in a map" Watch "Finding an element in a map" New topic
Author

Finding an element in a map

Neelesh Bodas
Ranch Hand

Joined: Jul 20, 2006
Posts: 107
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

Joined: Apr 25, 2005
Posts: 809
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


Asking Smart Questions FAQ - How To Put Your Code In Code Tags
 
jQuery in Action, 2nd edition
 
subject: Finding an element in a map
 
Similar Threads
Map Doubt
Retrieving data from Maps.
hashCode(), equals(): Got question right, but for the wrong reasons
can you please this doubt about hashcode()
Help on Hashcode