I\'m trying to add the below book objects to a TreeSet. However, when I debug the code, it says that the set has a size of 1 and only contains the first object added (book1). Wh
@Override
public int compareTo(Book o) {
// TODO Auto-generated method stub
return 0;
}
What Comparable#compareTo
return value says -
a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. documentation
When you added multiple object to tree set, 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.All the object are equals by Book
objects compareTo
method(provided) definition, so TreeSet just ignored duplicate object.
Solution: Define compareTo method correctly, keeping this thing in mind return value should negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.