我知道 hashmap 键应该是不可变的对象,或者至少有一个一致的 hashcode 以正确地从 Map/Set 中检索它的值。但是,如果我使用一个变异对象作为键而不覆盖哈希码或等于,它的哈希码是否会在其生命周期内保持一致。我试过它来检索变异对象的哈希码,并发现它始终一致。
最佳答案
Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified.
因此,如果您更改对象,则无法保证哈希码不会更改。碰巧某些 JDK 实现可能使用某种内部地址 but they don't have to所以你不应该依赖它。
关于java - 对象突变时默认哈希码是否更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11807233/