How to prevent null check before equals

Svish picture Svish · Oct 25, 2011 · Viewed 21.7k times · Source

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

pholser picture pholser · Oct 25, 2011

Java 7 offers java.util.Objects.equals.