[hashCode在更改参数时方法不会更改

问题描述 投票:-3回答:1

我面临一个问题。我正在尝试比较方法中两个对象的hashCodes。它显示了对象的两个不同的hashCodes,但是当我更改对象位置时,hashCode保持不变。这是代码的一部分:

public class Cat {
    public int age;
    public int weight;
    public int strength;

    public Cat() {
    }

    public boolean fight(Cat anotherCat) {
        int score = 0;
        if (this.age > anotherCat.age)
            score++;
        if (this.weight > anotherCat.weight)
            score++;
        if (this.strength > anotherCat.strength)
            score++;

        if ((this.weight == anotherCat.weight) && (this.strength == anotherCat.strength) && (this.age == anotherCat.age)) {
            long a = this.hashCode();
            long b = anotherCat.hashCode();
            System.out.println(a);
            System.out.println(b);


        }


        return score >= 2;
    }

    public static void main(String[] args) {
        Cat cat1 = new Cat();
        cat1.weight = 10;
        cat1.strength = 5;
        cat1.age = 7;
        Cat cat2 = new Cat();
        cat2.weight = 10;
        cat2.strength = 5;
        cat2.age = 7;
        System.out.println(cat1.fight(cat2));

    }
}
        cat1.fight(cat2)
        951007336
        2001049719 

        cat2.fight(cat1) 
        951007336
        2001049719  

为什么会这样?

java object methods hashcode
1个回答
0
投票

更改参数时方法中的hashCode不变

这是Object.hashCode的正常行为。您的Cat方法正在使用继承的hashCode

hashCodeObject的实现返回“身份哈希码”;即根据对象的身份(以某种方式)计算出的对象。在对象的生命周期中不会改变。

如果您希望哈希码值取决于对象的字段,那么您需要重写Object.hashCode;例如

   @Override
   public int hashCode() {
       return age + (weight * 31) + (strength * 31 * 67);
   }

但是请注意,不能保证哈希码的值是唯一的。唯一性不是equals / hashcode合同的一部分。

© www.soinside.com 2019 - 2024. All rights reserved.