Is there anywhere in the Java standard libraries that has a static equality function something like this?
public static <T> boolean equals(T a, T b)
{
if (a == null)
return b == null;
else if (b == null)
return false;
else
return a.equals(b);
}
I just implemented this in a new project Util
class, for the umpteenth time. Seems unbelievable that it wouldn't ship as a standard library function...
7. == and != The comparison and not equal to operators are allowed with null in Java.
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 .
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.
In JDK 7 there's Objects#equals(). From the Javadoc:
Returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals method of the first argument.
In addition to the already mentioned function in Apache Commons Lang there's also one in Google Guava, Objects#equal():
Java 7 onward we have JDK 7 Objects#equals().
You can look at the 3rd party libraries too :
Apache Commons ObjectUtils#equals() , Google's Guava Objects#equal() and Spring's ObjectUtils#nullSafeEquals().
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