Compare two objects in Java with possible null values
Leverage the power of Java's Objects.equals(Object a, Object b) for null-safe object comparisons. Here's how you use it:
It's your one-stop solution for handling null values, equating two null objects as true, and a null with a non-null object as false, all without the dreaded NullPointerException.
Legacy code: Handling null comparison
Working with Java versions prior to 7? No problem. You can implement a replica of Objects.equals:
This will mimic Objects.equals giving you a null-safe comparison.
Beware of null String traps!
Though Objects.equals is great, string comparison with null awareness requires special attention. Apache Commons Lang has StringUtils.equals to deal with these:
For Android enthusiasts, TextUtils.equals is just the tool for you:
Embrace nulls in sorting
When you play with collections and sorting, you might encounter null values. Here's how to create a null-safe comparator:
Complex objects? No problem! Chain your comparisons with Comparator's thenComparing:
Be vigilant: Watch out for these cases
Objects.equals is handy but not a magic wand. Be alert for special cases:
- Custom objects: Overridden
equalsmethod? If not, do it now! - Primitive types:
Objects.equalswon't play nice, use wrappers or direct comparisons. - Large collections: Beware the performance! Avoid unnecessary comparisons.
Common errors that will cost you
Common bugs to squash when comparing objects:
equalscontract violation: Should be reflective, symmetric, transitive, and consistent.- Forgotten about
hashCode: NoequalswithouthashCode, maintain their contract. - Comparing apples and oranges: Different types yield
false. - Sorted collections: Using custom comparator can alter the location and presence of
nullvalues.
Learn from the masters: Source code
Dive into StringUtils.equals's code for null-safe strings comparison:
Was this article helpful?