You are correct, when you want to use any of the Trees
(TreeMap
, TreeSet
) the objects you add must implement Comparable
.
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()
(like String
)
Then use this field for compareTo, if the values of the others are not important for equality.
(But then equals()
must also only use this one field)
Use EqualsBuilder
from Apache:
This works with reflection, and is not the fastest solution
Write it your own, read some tutorial how to do that: e.g:
Josh Bloch: Effective java 2nd Edition
But don't forget that equals()
, and compareTo()
must be compatible (and hashCode()
, 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
.