Compare two objects with a check for null

前端 未结 7 1156
鱼传尺愫
鱼传尺愫 2020-12-10 00:21

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, Obje         


        
相关标签:
7条回答
  • 2020-12-10 00:50

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

    0 讨论(0)
  • 2020-12-10 00:51

    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.

    0 讨论(0)
  • 2020-12-10 00:53

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

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

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

    0 讨论(0)
  • 2020-12-10 01:00

    Java 7.0 added a new handy class: Objects.

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

    0 讨论(0)
  • 2020-12-10 01:10
    public static boolean equals(Object object1, Object object2) {
        if (object1 == null || object2 == null) {
            return object1 == object2;
        }
        return object1.equals(object2);
    }
    
    0 讨论(0)
  • 2020-12-10 01:14

    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.

    0 讨论(0)
提交回复
热议问题