为什么覆盖equals方法一定要覆盖hashCode方法

2024-12-03 10:59:02
推荐回答(1个)
回答(1):

解决办法 复写hashcode方法
public class HashMapTest {
public static class CC {
private String cc;
public String getCc() {
return cc;
}
public void setCc(String cc) {
this.cc = cc;
}
public CC(String cc) {
this.cc = cc;
}
@Override
public boolean equals(Object arg0) {
CC testC = (CC) arg0;
return cc.equals(testC.getCc());
}
@Override
public int hashCode() {
return cc.hashCode();
}
}
public static void main(String[] args) {
Map map = new HashMap();
map.put(new CC("aa"), "bb");
System.out.println(map.get(new CC("aa")));
}
}

就可以正确获得结果
bb