有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java重写hashcode和等于强制所有实例是相同的

class Dog {
    private int variableA;
    private int variableB;
    private int variableC;
    public Dog(int A, int B, int C) {
        variableA = A;
        ...
    }

    @Override
    public int hashCode() {
        int result = 17;
        return result;
    }

    @Override
    public boolean equals(Object o) {
        if (o == this)
            return true;

        if (o instanceof Dog)
            return true;

        return false;
    }


Set<Dog> dogSet = new HashSet<>();
dogSet.add(new Dog(1,2,3))
dogSet.add(new Dog(2,3,4))

我想确保在dogSet中只有一个Dog实例

我相信我的hashCode()equals()实现了这一点。这是我实施的最佳实践吗

编辑
将有多种类型的狗和狗实际上是一个接口

public interface Dog
public class ShortDog extends Dog
public class BigDog extends Dog
public class OnlyOneDog extends Dog
...

实际上有一个名为DogHouse的类,其中存在这个哈希集

public class DogHouse
    private Set<Dog> dogSet = new HashSet<>();

我们可以有很多Dog(它们的子类型)的实例,但我想确保dogSet对于OnlyOneDog来说是唯一的,我打算用hashcode和equals实现这一点

我打算在OnlyOneDog中重写hashcode+equals。这是OnlyOneDog的特例

有更好的办法吗


共 (0) 个答案