aspose file tools*
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
Author

Object HashCode in HashMap

deepak_nagpal
Greenhorn

Joined: Jan 13, 2003
Posts: 1
Hi,

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?

Thanks,
Deepak
Å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
Rancher

Joined: Aug 05, 2005
Posts: 3446
    
  12
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


Joanne
 
jQuery in Action, 2nd edition
 
subject: Object HashCode in HashMap