Does Java have a general equality test that also handles NULL values?

Is there somewhere in the standard Java libraries that have 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 the new Util class, for the Util time. It seems unbelievable that it will not come as a standard library function ...

+6
source share
2 answers

In JDK 7, # equals () objects . From Javadoc:

Returns true if the arguments are equal to each other, and false otherwise. Therefore, if both arguments are null, true is returned, and if exactly one argument is null, false is returned. Otherwise, equality is determined using the equal method of the first argument.

In addition to the function already mentioned in Apache Commons Lang, there is also in Google Guava, Objects # equal () :

+13
source

Java 7 further we have JDK 7 Objects # equals () .

You can also see third-party libraries:

Apache Commons ObjectUtils # equals () , Google Guava Objects #equal () and Spring ObjectUtils # nullSafeEquals () .

+5
source

Source: https://habr.com/ru/post/947871/


All Articles