Java Notes
Comparing objects
Comparing objects is not at all as simple as with primitive values. The equality operators (== and !=) probably don't work as you expect (the compare the references to objects, not the values), and therefore are much less frequently used, and none of the other comparison operators are even legal with objects.
Use .equals() and .compareTo() methods instead of operators
- Equality is tested using
.equals()
, eg,a.equals(b)
. The == and != operators test to see if two object references are to the same object, and will be false if the two references are to different objects, even if they have the same value. Useequals()
unless you have a very special reason to use == or !=. - Inequality tests 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). - 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)
Equality comparison: Four ways for objects
Comparison | Objects |
---|---|
a == b , a != b |
Compares references, not values. The use of == with object references is generally limited to the following:
|
a.equals(b) |
Compares values for equality. Because this method is defined in the Object class,
from which all other classes are derived, it's automatically defined for every class.
However, it doesn't perform an intelligent comparison for most classes unless
the class overrides it. It has been defined in a meaningful way for
most Java core classes.
If it's not defined for a (user) class, it behaves the same as ==.
It turns out that defining |
a.compareTo(b) |
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, ...). |
compare(a, b) |
Comparator interface.
Compares values of two objects. This is implemented as part of the Comparator<T> interface,
and the typical use is to define one or more small utility classes that implement
this, to pass to methods such as sort() or
for use by sorting data structures such as TreeMap and TreeSet.
You might want to create a Comparator object for the following.
If your class objects have one natural sorting order, you may not need this. |
Comparing Object values with the equals()
Method
Use the equals()
method to compare object values.
The equals()
method returns a boolean value.
The previous example can be fixed by writing:
if (name.equals("Mickey Mouse")) // Compares values, not references.
Because the equals()
method makes a == test first, it can be
fairly fast when the objects are identical. It only compares the values if
the two references are not identical.
Comparing Object references with the ==
and !=
Operators
The two operators that can be used with object references are
comparing for equality (==
) and
inequality (!=
). 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") // Legal, but ALMOST SURELY WRONG
This is true only if name
is a reference to the same object that
"Mickey Mouse"
refers to. This will usually be false
if the String in name
was read from input or computed (eg, by putting
strings together or extracting a substring), even though name
really does have exactly those characters in it.
Many classes (eg, String
) define the equals()
method to compare the values of objects.
If you define a class whose objects will be compared, you need to write
the .equals()
method for it. In addition, if you use it with
hash tables you need to define .hashcode()
in addition because
hashcode is used as a quite test for probably equality.
.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.
Defining a Comparator object
As described in the table above on compare()
, you can create
Comparators to sort any arbitrary way for any class.
For example, the String class defines the CASE_INSENSITIVE_ORDER comparator.
Shouldn't .equals and .compareTo produce same result?
The general advice is that if a.equals(b)
is true, then
a.compareTo(b) == 0
should also be true.
Curiously, BigDecimal
violates this.
Look at the Java API documentation
for an explanation of the difference.
This seems wrong, although their implementation has some plausibility.
Null complicates object comparison
When comparing objects with .equals(), if the first object reference is null, a NPE
(Null Pointer Exception) will be generated. If there's any chance the first object reference is
null something like the following code should be used for equality comparison.
if ((a != null) && a.equals(b))) . . .
Because .equals() may not be fast, and if there's much chance that objects will
actually be equal, it is faster to test for to see if the references are to
the same object using == like this:
if ((a == b) || ((a != null) && a.equals(b))) . . .
Additional comparison methods in some classes
String has the specialized equalsIgnoreCase()
and compareToIgnoreCase()
.
String also supplies the constant String.CASE_INSENSITIVE_ORDER
Comparator.