gpt4 book ai didi

java - 您现在可以告诉我为什么不在此 HashSet 代码中调用 equals() 吗?

转载 作者:行者123 更新时间:2023-11-29 07:03:55 24 4
gpt4 key购买 nike

<分区>

这是我测试 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);

}

}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com