Reputation: 1548
I have one class Human, which contains two fields, age(int), and name(String). With eclipse, I override the hashCode() and equals() method with these two fields. I also create a Comparator based on the age field.
Now, I create a TreeSet object with the Comparator of age, and also two instances (with different fields values) of Human class. Then I add these two objects into the set, however, there are always only one object in the set.
For understanding the problem, I print out the hash value of these two objects, and find them are different. Then, I test their equals() method, it does output false when I compare two instances with different field values. So now, I cannot figure out why the TreeSet can't handle (differentiate) the problem. Can anyone give me some help ? Thanks a lot !
Upvotes: 0
Views: 1652
Reputation: 691645
TreeSet doesn't use hashCode()
and equals()
at all. It uses the comparator you pass as argument (or the compareTo()
method of the objects if they are Comparable and you don't provide a comparator). Two objects are considered equal by a TreeSet if compare()
(orcompareTo()
) returns 0 when comparing these two objects.
So if your comparator only compares the age of humans, all the humans with the same age will be considered equal. If you want humans to be considered equal when they have the same age and name, then the comparator should compare by age, and then compare by name if the age comparison returns 0.
Upvotes: 4
Reputation: 120178
This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.
Upvotes: 2