This is my example code to test HashSet. I expect that the result is [3K,1K] but the this code results in [1K,3K,3K]
Could you let me know why the code not call 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);
}
}