Java Notes
Comparing objects using compareTo
Use compareTo(), not <, <=, >, >=
.
The inequality operators that work with primitives can not be used with
objects. Use compareTo()
instead.
Use .equals() and .compareTo() methods instead of operators
- Inequality tests on the value of objects use
a.compareTo(b)
instead of the comparison operators (>, >=, <, <=), which are illegal with objects. - Predefined Java classesb> (eg, String) that have meaningful comparisons
define
.equals()
and.compareTo()
. - User-defined classes must define
.equals()
and.compareTo()
if objects from the class are ever going to be compared (eg, for searching and sorting). See Overriding equals() and Implementing Comparable - compareTo() . - You can define a Comparator to use with any class.
This is often useful if you have data that you wish to sort
by different criteria. This implements
comp.compare(a, b)
(where comp is a Comparator) . See Comparators .
Comparable interface. Compares values and returns an int which tells if the values compare less than, equal, or greater than. If your class objects have a natural order, implement the Comparable<T> interface and define this method. All Java classes that have a natural ordering implement this (String, Double, BigInteger, ...).
.compareTo()
method of the Comparable<T> interface
The equals
method and ==
and !=
operators
test for equality/inequality, but
do not provide a way to test for relative values.
Some classes (eg, String and other classes with a natural ordering) implement
the Comparable<T> interface, which defines
a compareTo
method. You will want to implement Comparable<T> in
your class if you want to use it with Collections.sort() or Arrays.sort() methods.
a.compareTo(b)==0 should be the same as a.equals(b)
If you are defining your own class, when a.equals(b)
is true,
then a.compareTo(b) == 0
should also be true.
This is true for the library classes that implement compareTo, except
for BigDecimal
which violates this good convention.
Look at the Java API documentation
for an explanation of the difference.
This seems wrong, although their implementation has some plausibility.
Additional comparison methods in some classes
String has the specialized equalsIgnoreCase()
and compareToIgnoreCase()
.
String also supplies the constant String.CASE_INSENSITIVE_ORDER
Comparator.