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

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

    Not that this is neccessarily an answer to your question, it is just an example of when I find it useful that the behaviour is how it is now.

    private static final String CONSTANT_STRING = "Some value";
    String text = getText();  // Whatever getText() might be, possibly returning null.
    

    As it stands I can do.

    if (CONSTANT_STRING.equals(text)) {
        // do something.
    }
    

    And I have no chance of getting a NullPointerException. If it were changed as you suggested, I would be back to having to do:

    if (text != null && text.equals(CONSTANT_STRING)) {
        // do something.
    }
    

    Is this a good enough reason for the behaviour to be as it is?? I don't know, but it is a useful side-effect.

提交回复
热议问题