Compare two objects with a check for null

前端 未结 7 1263
鱼传尺愫
鱼传尺愫 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: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.

提交回复
热议问题