| Comparison |
Primitives |
Objects |
| a == b, a != b |
Equal values |
Refer to the same object. |
| a.equals(b) |
N/A |
Compares values, if it’s defined for this class, as it is for most Java core classes. If it’s not defined for a (user) class, it behaves the same as ==. |
| a.compareTo(b) |
N/A |
Compares values. Class must implement the Comparable interface. All Java classes that have a natural ordering implement this (String, Double, BigInteger, …), but BigDecimal may not do what you expect. Comparable objects can be used by the Collections sort() method and data structures that implicitly sort (eg, TreeSet, TreeMap). |
| compareTo(a, b) |
N/A |
Compares values. Available only if the Comparator interface has been implemented, which is not the case for the Java classes. Typically used to define a comparator object that can be passed to Collections sort() method or ordered data structures. |