liveBook · Manning

Objects.equals

As explained in 100 Java Mistakes and How to Avoid Them

Objects.equals is a Java utility method that compares two references for equality while treating two null references as equal.

Objects.equals compares two references while handling null safely: two null values compare equal, and a null value does not trigger a method call. Use it for nullable fields inside equals(). section 7.6

Null-safe field comparison

Replace a fragile expression such as data != null && data.equals(that.data) with Objects.equals(data, that.data). This makes new Box(null).equals(new Box(null)) return true instead of false. section 7.6

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains the null-handling failure and correction, but does not develop the complete equals() contract.
Examples
Uses Box.equals() with null data and a User.equals() implementation containing Objects.equals() field comparisons.
What it assumes
Assumes familiarity with Java equals() implementations and nullable object fields.
What you can do after
Apply it when comparing nullable fields to avoid asymmetric null checks and incorrect equality results.
How it connects
Connects nullable equality with equals(), HashMap, ArrayList, HashSet, and static analysis.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.