0xbe5077ed
0xbe5077ed

Reputation: 4755

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

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

Upvotes: 6

Views: 144

Answers (2)

martido
martido

Reputation: 383

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

Upvotes: 13

AllTooSir
AllTooSir

Reputation: 49372

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

Upvotes: 5

Related Questions