Java, Object.hashCode() result constant across all JVMs/Systems?

前端 未结 6 1368
傲寒
傲寒 2020-12-05 21:17

Is the output of Object.hashCode() required to be the same on all JVM implementations for the same Object?

For example if \"test\".hashCode()

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 21:40

    As noted, for many implementations the default behavior of hashCode() is to return the address of the object. Obviously this can be different each time the program is run. This is also consistent with the default behavior of equals(): two objects are equal only if they are the same object (where x and y are both non-null, x.equals(y) if and only if x == y).

    For any classes where hashCode() and equals() are overridden, generally they are calculated in a deterministic way based on the values of some or all of the members. Thus, in practice it is likely that if an object in one run of the program can be said to be equal to an object in another run of the program, and the source code is the same (including such things as the source code for String.hashCode() if that is called by the hashCode() override), the hash codes will be the same.

    It is not guaranteed, although it is hard to think of a reasonable real-world example.

提交回复
热议问题