File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Object HashCode in HashMap

 
deepak_nagpal
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 208
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Joanne Neal
Rancher
Pie
Posts: 3742
16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic