File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Object HashCode in HashMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Object HashCode in HashMap" Watch "Object HashCode in HashMap" New topic

Object HashCode in HashMap


Joined: Jan 13, 2003
Posts: 1

1. Is it possible for two objects with the same hashcode to act as keys in a hashtable? If yes, then please give me some examples.

2. I know If I want to sort objects (like employee objects) in a HashMap, I need to make my Object ((like employee objects)) which acts as the key in the HashMap entry to implement the Comparator interface and then implement the compare method which will sort on say employee salary. Can you please tell me how can I implement the equals method at the same time while sorting objects?

Ådne Brunborg
Ranch Hand

Joined: Aug 05, 2005
Posts: 208
1. Yes. Keys are compared by the equals() method. If they have the same hashCode, it is just not as efficient. The following is a perfeclty legal, but very poor quality code, since the hashCode is only depening on the length of one String - name.

2. In order to sort, you need to implement the compareTo method, which doesn't have to be related to the equals() method at all.

[ November 15, 2006: Message edited by: �dne Brunborg ]

Entia non sunt multiplicanda praeter necessitatem
Joanne Neal

Joined: Aug 05, 2005
Posts: 3742
Originally posted by deepak_nagpal:

2. I know If I want to sort objects (like employee objects) in a HashMap,

You can't sort objects in a HashMap. From the HashMap api doc
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

If you want a sorted map, use a TreeMap

I agree. Here's the link:
subject: Object HashCode in HashMap
It's not a secret anymore!