What is the reason behind Enum.hashCode()?

后端 未结 7 684
醉酒成梦
醉酒成梦 2020-12-01 02:32

The method hashCode() in class Enum is final and defined as super.hashCode(), which means it returns a number based on the address of the instance, which is a random number

7条回答
  •  醉酒成梦
    2020-12-01 03:19

    I think that the reason they made it final is to avoid developers shooting themselves in the foot by rewriting a suboptimal (or even incorrect) hashCode.

    Regarding the chosen implementation: it's not stable across JVMs, but it's very fast, avoid collisions, and doesn't need an additional field in the enum. Given the normally small number of instances of an enum class, and the speed of the equals method, I wouldn't be surprised if the HashMap lookup time was bigger with your algorithm than with the current one, due to its additional complexity.

提交回复
热议问题