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

前端 未结 12 697
借酒劲吻你
借酒劲吻你 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:23

    This is a tricky question. For backward compatability you can't do so.

    Imagine the following scenario

    void m (Object o) {
     if (one.equals (o)) {}
     else if (two.equals (o)) {}
     else {}
    }
    

    Now with equals returning false else clause will get executed, but not when throwing an exception.

    Also null is not really equal to say "2" so it makes perfect sense to return false. Then it is probably better to insist null.equals("b") to return also false :))

    But this requirement does make a strange and non symmetric equals relation.

提交回复
热议问题