小编Krz*_*Hal的帖子

Java HashSet add()方法不会调用重写的equals()方法

我有这个代码:

@Override
public boolean equals(Object obj) {

    System.out.println("equals called");

    if(this == obj) {
        System.out.println("THIS object is the same as OBJ");
        return true;
    }

    System.out.println("obj.getClass() is " + obj.getClass());
    System.out.println("this.getClass() is " + this.getClass());
    if ((obj == null) || (obj.getClass() != this.getClass())) {
        return false;
    }

    double objOrbitalPeriod = ((HeavenlyBody) obj).getOrbitalPeriod();
    return this.orbitalPeriod == objOrbitalPeriod;
}

@Override
public int hashCode() {
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在主要代码是:

private static Set<Planet> solarSystem = new HashSet<>();
public static void main(String[] args) {
    Planet planet = …
Run Code Online (Sandbox Code Playgroud)

java equals

3
推荐指数
1
解决办法
144
查看次数

标签 统计

equals ×1

java ×1