This question already has an answer here:
I was looking for something akin to the Java TreeSet's ability to receive a custom comparator at instantiation time, so I needed not to use the object's default equality (and hash code) criteria.
The closest I could come up with was to wrap my objects in a private custom class, but that seems hacky :( This ends up being a kind of recurring theme when programming, so I was wondering if there's something already available for us to use. Maybe in the commons libraries?
Thanks
There are a couple of third-party collections frameworks that allows custom equality logic. This is perfect for overriding equality for objects that you can't alter the source.
Nope, you've found exactly the solution you're supposed to use.
Even for
TreeSet
, it's frowned upon to use comparison criteria that aren't compatible withequals
:(I don't know about Apache Commons, but Guava specifically rejected requests for this sort of thing.)
You are correct, when you want to use any of the
Trees
(TreeMap
,TreeSet
) the objects you add must implementComparable
.For primitive types, Java has solved this for you.
For custom objects you have 3 possibilities:
One of your object already has an unique id of a primitive type or an Type that already implements
compareTo()
(likeString
) Then use this field for compareTo, if the values of the others are not important for equality. (But thenequals()
must also only use this one field)Use
EqualsBuilder
from Apache: This works with reflection, and is not the fastest solutionWrite it your own, read some tutorial how to do that: e.g:
But don't forget that
equals()
, andcompareTo()
must be compatible (andhashCode()
, too), such that you do not violate the equals contract. (The contract itself is less understandable, but it gets clear if you foillow one of that equals tutorials.)Or forget that all, and use a
HashSet
,HashMap
.