Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java have generic test for equality that also handles nulls?

Tags:

java

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

like image 825
0xbe5077ed Avatar asked Jun 21 '13 21:06

0xbe5077ed


People also ask

Can you do == null in Java?

7. == and != The comparison and not equal to operators are allowed with null in Java.

Can you use == for null?

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 .

Can we compare two null values in Java?

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.


2 Answers

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():

like image 178
martido Avatar answered Oct 20 '22 00:10

martido


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

like image 38
AllTooSir Avatar answered Oct 19 '22 23:10

AllTooSir