Compare two objects with a check for null

dcstraw picture dcstraw · Sep 9, 2009 · Viewed 33k times · Source

Is there a method in the JDK that compares two objects for equality, accounting for nulls? Something like this:

public static boolean equals(Object o1, Object o2)
{
    if (o1 == null)
    {
        return o2 == null; // Two nulls are considered equal
    }
    else if (o2 == null)
    {
        return false;
    }

    return o1.equals(o2);
}

It seems silly to write this method myself since I would think that it has to exist already somewhere.

Answer

icza picture icza · Sep 3, 2014

Java 7.0 added a new handy class: Objects.

It has a method exactly for this: Objects.equals(Object a, Object b)