Skip to Content
100 Java Mistakes and How to Avoid Them
book

100 Java Mistakes and How to Avoid Them

by Tagir Valeev
May 2024
Intermediate to advanced content levelIntermediate to advanced
352 pages
10h 45m
English
Manning Publications
Content preview from 100 Java Mistakes and How to Avoid Them

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

The Complete Coding Interview Guide in Java

The Complete Coding Interview Guide in Java

Anghel Leonard
Java Coding Problems

Java Coding Problems

Anghel Leonard
Modern Java in Action

Modern Java in Action

Raoul-Gabriel Urma, Mario Fusco, Alan Mycroft

Publisher Resources

ISBN: 9781633437968Supplemental ContentPublisher SupportOtherPublisher WebsiteSupplemental ContentErrata PagePurchase Link