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

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

    An exception really should be an exceptional situation. A null pointer might not be a programmer error.

    You quoted the existing contract. If you decide to go against convention, after all this time, when every Java developer expects equals to return false, you'll be doing something unexpected and unwelcome that will make your class a pariah.

    I could't disagree more. I would not rewrite equals to throw an exception all the time. I'd replace any class that did that if I were its client.

提交回复
热议问题