What is the reason behind Enum.hashCode()?

后端 未结 7 686
醉酒成梦
醉酒成梦 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:12

    There is no requirement for hash codes to be deterministic between JVMs and no advantage gained if they were. If you are relying on this fact you are using them wrong.

    As only one instance of each enum value exists, Object.hashcode() is guaranteed never to collide, is good code reuse and is very fast.

    If equality is defined by identity, then Object.hashcode() will always give the best performance.

    The determinism of other hash codes is just a side effect of their implementation. As their equality is usually defined by field values, mixing in non-deterministic values would be a waste of time.

提交回复
热议问题