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 ...
Get 100 Java Mistakes and How to Avoid Them now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.