Svish Svish - 17 days ago 5
Java Question

How to prevent null check before equals

I find stuff like this rather annoying and ugly in

equals
methods:

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?

Answer

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

http://commons.apache.org/lang/

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

Comments