equals() without hashCode()

前端 未结 7 864
自闭症患者
自闭症患者 2020-12-20 21:17

Can I only implement equals() but not hashCode() if I only need to compare objects and not yet plan to put the objects into any hash based containers?

Seems all Jav

7条回答
  •  我在风中等你
    2020-12-20 22:23

    You can, but you'll be breaking the general contract of equals, and this will lead to weird bugs. Even if you don't think you're using the hash codes, any external code you pass the objects to might rely on them, even if it doesn't seem to be hash-based. If you're not going to give your objects a decent hash method, at least make it throw a runtime exception. It's almost always better to give your objects a decent hashCode, though.

提交回复
热议问题