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(), and compareTo()
  • 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.

7.1 Mistake 55: Use of reference equality instead of the equals method

 
 

7.2 Mistake 56: Assuming equals() compares content

 
 
 

7.3 Mistake 57: Using URL.equals()

 
 

7.4 Mistake 58: Comparing BigDecimals with different scales

 
 
 

7.5 Mistake 59: Using equals() on unrelated types

 
 

7.6 Mistake 60: Malformed equals() implementation

 
 
 

7.7 Mistake 61: Wrong hashCode() with array fields

 
 
 

7.8 Mistake 62: Mismatch between equals() and hashCode()

 
 

7.9 Mistake 63: Relying on a particular return value of compare()

 
 

Summary

 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest