Compare two objects with a check for null

2019-01-18 17:26发布

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.

7条回答
一纸荒年 Trace。
2楼-- · 2019-01-18 18:04

FWIW, this was my implementation:

private static boolean equals(Object a, Object b) {
    return a == b || (a != null && a.equals(b));
}

In my application, I know that a and b will always be the same type, but I suspect this works fine even if they aren't, provided that a.equals() is reasonably implemented.

查看更多
一纸荒年 Trace。
3楼-- · 2019-01-18 18:10

Whenever I come across a need and think "this is so common Java must have it" but find it doesn't, I check the Jakarta Commons project. It almost always has it. A quick search of the commons-lang API (which has the most basic of common utilities) shows an equals() method that provides what you want.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-01-18 18:11

Apache Commons Lang has such a method: ObjectUtils.equals(object1, object2). You don't want generics on such a method, it will lead to bogus compilation errors, at least in general use. Equals knows very well (or should - it is part of the contract) to check the class of the object and return false, so it doesn't need any additional type safety.

查看更多
放荡不羁爱自由
5楼-- · 2019-01-18 18:15

Java 7.0 added a new handy class: Objects.

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

查看更多
Emotional °昔
6楼-- · 2019-01-18 18:16
public static boolean equals(Object object1, Object object2) {
    if (object1 == null || object2 == null) {
        return object1 == object2;
    }
    return object1.equals(object2);
}
查看更多
狗以群分
7楼-- · 2019-01-18 18:18
登录 后发表回答