7 Comparing objects
This chapter covers
- Why you should not use reference equality for boxed types
- Standard classes for which the
equals()
method behaves unexpectedly or is not defined at all - How to properly implement
equals()
,hashCode()
,compare()
, andcompareTo()
- What can happen if you use a malformed comparison method
Object comparison is exceptionally important in Java. There are several methods associated with object comparison: equals()
, hashCode()
, Comparable
.compareTo()
, and Comparator.compare()
. They are used implicitly by many algorithms (e.g., Arrays.sort()
) and data structures (e.g., HashMap
). Failure to implement them correctly may lead to annoying, difficult-to-debug problems.
If you are going to implement any of these methods, there’s good news and bad news. The good news is that the contracts for these methods are perfectly specified in the Java documentation. The algorithms will function correctly, as long as you strictly follow the contracts. The bad news is that the contracts are somewhat tricky to implement, and there are many ways to screw things up.
Even if you don’t implement these methods by yourself, you should be careful when using them. For some classes, equals()
behaves in an unexpected way. There’s also the reference equality operator ==
, which adds confusion, as sometimes, people mistakenly use ==
instead of equals()
, or vice versa.