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 !
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.