To accomplish the other answers:
Implementing the Comparable
interface only makes sense for classes who really have a natural ordering. Additionally, this ordering should be consistent with the equals
method. Implementing the equals
and the compareTo
methods sounds easier, than it sometimes really is. This should be well-designed.
Often enough, there is no real natural ordering on the objects of a class. But you will have tasks to order them on a specific property, nevertheless. For this kind of tasks, you can implement another interface: Comparator
. A comparator then can be used to order your objects as you need.
Take a look at TreeSet
, which is such a search tree. This Set
implementation provides two constructors: One is designed for being used with objects that are comparable. The other takes a comparator for that task, and is designed for being used with non-comparable objects.