为啥覆盖了equals方法一定要覆盖hashcode方法
为什么覆盖了equals方法一定要覆盖hashcode方法?
1 测试代码
因为覆盖了equals方法因此希望得到的结果应该是"bb",但是因为没有覆盖hashcode方法,所以实际得到的是null
因为两个new CC("aa")的hashcode的值不同,所以实际上在hashmap
中是找不到值得。
解决办法 复写hashcode方法
就可以正确获得结果
bb
1 测试代码
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()); } } public static void main(String[] args) { Map<CC,String> map = new HashMap<CC,String>(); map.put(new CC("aa"), "bb"); System.out.println(map.get(new CC("aa"))); } }
因为覆盖了equals方法因此希望得到的结果应该是"bb",但是因为没有覆盖hashcode方法,所以实际得到的是null
因为两个new CC("aa")的hashcode的值不同,所以实际上在hashmap
中是找不到值得。
解决办法 复写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<CC,String> map = new HashMap<CC,String>(); map.put(new CC("aa"), "bb"); System.out.println(map.get(new CC("aa"))); } }
就可以正确获得结果
bb