What are ways to keep hashCode/equals consistent with the business definition of the class?

后端 未结 6 2079
萌比男神i
萌比男神i 2021-02-01 19:12

Object javadocs and Josh Bloch tell us a great deal about how hashCode/equals should be implemented, and good IDEs will handle fields of various types correctly. Some discussio

6条回答
  •  攒了一身酷
    2021-02-01 19:44

    You don't need to include every field in your hash code method. If you used more than one field in your hash code algorithm then the chances are it will remain good. The IDE-generated algorithms I've seen use a random (at the time of implementation, not at execution) prime constant value, so just make sure that classes that could end up in the same map or tree together (e.g. they implement the same interface) have different constant values. Unless, of course, you want equality at the interface level.

    I've never seen a hash code algorithm "go bad" - you're worrying a disproportionate amount about this.

提交回复
热议问题