|Equal values||Refer to the same object.|
|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 ==.|
|N/A||Compares values. Class must implement the Comparable<T> 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).|
|N/A||Compares values. Available only if the Comparator<T> 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.|
The two operators that can be used with object references are
comparing for equality (
!=). These operators
compare two values to see if they refer to the same object.
Although this comparison is very fast, it is often not what you want.
Usually you want to know if the objects have the same value, and not whether two objects are a reference to the same object. For example,
if (name == "Mickey Mouse") // ALMOST SURELY WRONG
This be true if
name is a reference to the same object that
"Mickey Mouse" refers to. This will probably be false
if the String in
name was read from input or computed (by putting
strings together or taking the substring), even though
really does have exactly those characters in it.
Many classes (eg,
String) define the
method to compare the values of objects.
equals() method to compare object values.
equals() method returns a boolean value.
The previous example can be fixed by writing:
if (name.equals("Mickey Mouse")) // Compares values, not referernces.
equals method and
test for equality/inequality, but
do not provide a way to test for the relative values.
Some classes (eg, String and other classes with a natural ordering) implement
the Comparable<T> interface, which defines
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.
The String class also provides case insensitive comparisons.
Comparing objects is somewhat awkward, so a === operator has been proposed.
a === b would be the same as
((a == b) || ((a != null) && a.equals(b)))
==to see if they are the same object, or
equals()to see if they may be a different object, but have the same value. This kind of error can be very hard to find.