[ACCEPTED]-Compare two objects with a check for null-java

Accepted answer
Score: 76

Java 7.0 added a new handy class: Objects.

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

Score: 17

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

Score: 16

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 4 know that a and b will always be the same 3 type, but I suspect this works fine even 2 if they aren't, provided that a.equals() is 1 reasonably implemented.

Score: 5
public static boolean equals(Object object1, Object object2) {
    if (object1 == null || object2 == null) {
        return object1 == object2;
    }
    return object1.equals(object2);
}

0

Score: 4

If you are worried about NullPointerExceptions 6 you could just test equality like:

if (obj1 != null && obj1.equals(obj2)) { ... }

The general 5 contract of equals() is that a non-null object should 4 never be equal to a null reference, and 3 that the equals() method should return false if 2 you are comparing an object to a null reference 1 (and not throw a NPE).

Score: 2

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

Score: 1

Jakarta Commons Lang API has what you are looking for ObjectUtils.equals(Object,Object)

0

More Related questions