user3139563
user3139563

Reputation: 180

Java contains() not in accordance with equals()

I have a custom class with overriden equals() and hashCode() methods. I store instances of that class in a TreeSet. I cannot figure out why the tree.contains(someObject) returns true, while tree.first().equals(someObject) returns false, in the case when the tree has only one element.

Upvotes: 0

Views: 90

Answers (2)

bvdb
bvdb

Reputation: 24760

Actually you should implement Comparable but you should also override the equals. Both are required.

Further more, you should make sure that the compareTo method always returns 0 when the equals would return true. If the equals would return false, then also the compareTo should return a value != 0.

Implementing hashCode is necessary if you wanted to use a HashMap instead. So, it's probably a good idea to implement it as well.

EDIT:

For those who wonder about Comparator: This interface is used when you want to use different kinds of sorting from time to time. In that case you create an additional class which acts as a sorter. This class then needs to implement the Comparator interface. So in this case you don't want your class to implement it.

Upvotes: 2

akhil_mittal
akhil_mittal

Reputation: 24167

As per doc for TreeSet:

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.

If you instantiate a TreeSet without an explicit comparator, it expects inserted elements to implement Comparable. It seems you have not done that.

Upvotes: 1

Related Questions