Comparable and Comparator
suggest changeVersions
[{“Name”:“Java SE 1.2”,“GroupName”:null},{“Name”:“Java SE 1.3”,“GroupName”:null},{“Name”:“Java SE 1.4”,“GroupName”:null},{“Name”:“Java SE 5”,“GroupName”:null},{“Name”:“Java SE 6”,“GroupName”:null},{“Name”:“Java SE 7”,“GroupName”:null},{“Name”:“Java SE 8”,“GroupName”:null},{“Name”:“Java SE 9 (Early Access)”,“GroupName”:null}]
Syntax
- public class MyClass implements Comparable
<MyClass
> - public class MyComparator implements Comparator
<SomeOtherClass
> - public int compareTo(MyClass other)
- public int compare(SomeOtherClass o1, SomeOtherClass o2)
Remarks
When implementing a compareTo(..)
method which depends upon a double
, do not do the following:
public int comareTo(MyClass other) {
return (int)(doubleField - other.doubleField); //THIS IS BAD
}
The truncation caused by the (int)
cast will cause the method to sometimes incorrectly return 0
instead of a positive or negative number, and can thus lead to comparison and sorting bugs.
Instead, the simplest correct implementation is to use Double.compare, as such:
public int comareTo(MyClass other) {
return Double.compare(doubleField,other.doubleField); //THIS IS GOOD
}
A non-generic version of Comparable<T>
, simply Comparable
, has existed since Java 1.2. Other than for interfacing with legacy code, it’s always better to implement the generic version Comparable<T>
, as it doesn’t require casting upon comparison.
It is very standard for a class to be comparable to itself, as in:
public class A implements Comparable<A>
While it is possible to break from this paradigm, be cautious when doing so.
A Comparator<T>
can still be used on instances of a class if that class implements Comparable<T>
. In this case, the Comparator
’s logic will be used; the natural ordering specified by the Comparable
implementation will be ignored.