【问题标题】:Could you let me now why not call equals() in this HashSet code? [closed]现在你能告诉我为什么不在这个 HashSet 代码中调用 equals() 吗? [关闭]
【发布时间】:2014-02-26 14:39:47
【问题描述】:

这是我测试 HashSet 的示例代码。 我希望结果是 [3K,1K] 但此代码导致 [1K,3K,3K]

你能告诉我为什么代码没有调用equals吗?

import java.util.HashSet;

class SutdaCard{

    private int num;
    private boolean isKwang;

    SutdaCard(){
        this(1,true);
    }
    SutdaCard(int num, boolean isKwang){
        this.num = num;
        this.isKwang = isKwang;
    }

    public String toString(){
        return num+(isKwang ? "K":"");
    }

    public boolean equals(Object obj){
        String compareValue = obj.toString();
        String thisValue = toString();

        System.out.println("equals");

        return thisValue.equals(compareValue);
    }

    public int hashcode(){
        return toString().hashCode();
    }

}
class exercise11_11 {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub      

        HashSet<SutdaCard> set = new HashSet<SutdaCard>();


        set.add(new SutdaCard(3,true));
        set.add(new SutdaCard(3,true));
        set.add(new SutdaCard(1,true));

        System.out.println(set);

    }

}

【问题讨论】:

  • 如果这是您的代码,那么您在 hashCode 方法名称中有错字(小写 c)。
  • 并且由于@PavelHoral 注意到的结果,当 HashSet 调用真正的 hashCode 时,它​​会为您的三个项目中的每一个获得不同的值,并且根据规范,它们因此不能相等(所以不调用equals)
  • 并使用 @Override 注释来确保您正在覆盖 smth
  • 如果你重写方法(这里是 hashCode 和 equals)你应该总是用 @Override 注释这些方法。然后编译器检查该方法是否确实被覆盖。在您的情况下,您会收到方法哈希码的编译器错误,因为这不会覆盖 Object 类中的任何方法。
  • 谢谢大家!!我解决了。

标签: java hashset


【解决方案1】:

您没有正确覆盖hashCode()。试试:

@Override
public int hashCode() {
    return this.toString().hashCode();
}

由于Set 在您的代码中使用来自ObjecthashCode(),因此两个SutdaCards 哈希码将不匹配,并且永远不会调用equals()

如果您添加@Override 注释,编译器将检查您是否确实覆盖了某些内容,如果您有拼写错误,则生成警告。

【讨论】:

  • 但这是隐式可用的?您的解决方案是使用“this”关键字或“@override”?
  • 出于同样的原因,您还应该将@Override 添加到equalstoString 方法中。所有这些方法都会覆盖 Java Object class 的默认值。
猜你喜欢
  • 2013-05-10
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
  • 2015-09-12
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
  • 1970-01-01
相关资源
最近更新 更多