• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

TreeSet and compareTo Java 5

 
Ranch Hand
Posts: 153
3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hallo I have the following class



I want to add instances of this class to a TreeSet.
As far I have understood Sets you should be able to add an element which is not already contained in this set. To test this the equals() method is used.
When I try to put two different instances of the above class, which differ only in the jarFile field but have the same name value (compareTo returns 0) only the first instance is put into the TreeSet.
When I switch to a HashSet both instances are put into the Set.



Output:


This is totally unexpectated behavior for me, since I thought that only equals() is used to determined if an instance can be put into a Set, and compareTo() is only used for ordering.

Can anybody explain this behavior???

Many thanks,

Hans
 
Ranch Hand
Posts: 121
IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Extracted from http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeSet.html
:

"This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the set, equal."
 
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A HashSet will use the hashCode method first to compare two objects. If two objects return different hashCodes they are assumed to be different and the HashSet will not call either the equals or comapreTo method. As JarFile does not override hashCode it will use Object's implementation.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects.



So as your hashCode method uses the JarFile hashCode method, unless the two JarFiles are the same object, it is very likely two different JClass objects will return different values from hashCode.
reply
    Bookmark Topic Watch Topic
  • New Topic