Is there a method in the JDK that compares two objects for equality, accounting for nulls? Something like this:
public static boolean equals(Object o1, Object o2) { if (o1 == null) { return o2 == null; // Two nulls are considered equal } else if (o2 == null) { return false; } return o1.equals(o2); }
It seems silly to write this method myself since I would think that it has to exist already somewhere.
The compare() method in StringUtils class is a null-safe version of the compareTo() method of String class and handles null values by considering a null value less than a non-null value. Two null values are considered equal.
equals(null) will always be false. The program uses the equals() method to compare an object with null . This comparison will always return false, since the object is not null .
Using equals() method of the Object class In the same way the equals() method of the object class accepts two String values and returns a boolean value, which is true if both are equal (or, null) and false if not.
7. == and != The comparison and not equal to operators are allowed with null in Java.
Java 7.0 added a new handy class: Objects
.
It has a method exactly for this: Objects.equals(Object a, Object b)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With