Svish Svish - 8 months ago 39
Java Question

How to prevent null check before equals

I find stuff like this rather annoying and ugly in


if (field == null)
if (other.field != null)
return false;
else if ( ! field.equals(other.field))
return false;

In C# I could've done this:

if( ! Object.Equals(field, other.field))
return false;

Is there something similar in Java, or what is the preferred way to do this kind if thing?


Use commons-lang:

org.apache.commons.lang.ObjectUtils.equals(Object object1, Object object2)

Source code:

public static boolean equals(Object object1, Object object2) {
    if (object1 == object2) {
        return true;
    if ((object1 == null) || (object2 == null)) {
        return false;
    return object1.equals(object2);

From Apache

That's about equivalent to what you do in C#