Is it a bad idea if equals(null) throws NullPointerException instead?

前端 未结 12 746
借酒劲吻你
借酒劲吻你 2020-12-02 07:00

The contract of equals with regards to null, is as follows:

For any non-null reference value x, x.equals(null) sho

12条回答
  •  广开言路
    2020-12-02 07:30

    You should return false if the parameter is null.

    To show that this is the standard, see 'Objects.equals(Object, Object) from java.util, that performs an assymetric null check on the first parameter only (on which equals(Object) will be called). From the OpenJDK SE 11 source code (SE 1.7 contains exactly the same):

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

    This also handles two null values as equal.

提交回复
热议问题