File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes hashCode() used for searching is right? 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 » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "hashCode() used for searching is right?" Watch "hashCode() used for searching is right?" New topic

hashCode() used for searching is right?

nagaraj raja
Ranch Hand

Joined: Aug 06, 2005
Posts: 36
hai i am thinking Hashtable,HashMap,HashSet are implemented hashing mechanisem ie it will generate hashCode this is useful searching the elements in a collection this is my openion os hashing is it right??
marc weber

Joined: Aug 31, 2004
Posts: 11343

Yes, the primary benefit of hashCode is fast lookup.

Imagine a library with numerous rows of bookshelves. If you're looking for a particular book, it would be a lot faster if you knew what particular row of shelves to look in, rather than searching through the entire library. Of course, when you've found the correct shelves (indicated by hashCode), there might be other books on those shelves (because different objects might return the same hashCode), but you've narrowed your search to a much smaller region.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Philip Heller
Ranch Hand

Joined: Oct 24, 2000
Posts: 119
You're right, hash codes are used for efficient storage in collections. But as for sorting, only collections whose names begin with "Tree" sort their elements. See Chapter 8 of "Complete Java 2 Certification" for more.

-- Phil

Consultant to SCJP team.<br />Co-designer of SCJD exam.<br />Co-author of "Complete Java 2 Certification Study Guide".<br />Author of "Ground-Up Java".
Arulkumar Gopalan
Ranch Hand

Joined: Oct 13, 2003
Posts: 104
boolean equals(Object o) method also uses the hashing mechanism to compare object references.

Anbudan & Mahalo,<br />Arul<br /> <br />-Not a sun certified Java professional :-)
I agree. Here's the link:
subject: hashCode() used for searching is right?
It's not a secret anymore!