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

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.