Java collections - overriding equals and hashCode

房东的猫 提交于 2019-12-12 00:33:30

问题


class Hash {
  int a;

  Hash(int h){
    a=h;
  }

  public boolean equals(Object o) {     
    Boolean h=super.equals(o);
    System.out.println("Inside equals ");
    return h;
  }

  public int hashCode() {    
    System.out.println("Inside Hash");    
    return 2;
  }    
}

public class Eq {    
  public static void main(String...r) {    
    HashMap<Hash,Integer> map=new HashMap<Hash,Integer>();    
    Hash j=new Hash(2);    
    map.put(j,1);
    map.put(j,2);
    System.out.println(map.size());
  }
}

output was

inside hash

inside hash
1

Since it returns the same hashcode , the second time an object is added in hashmap it must use the equals method but it doesnt call . So wats the problem here?


回答1:


The HashMap is testing with == before .equals, and since you are putting the same object twice, the first test passes. Try with:

    Hash j=new Hash(2);
    Hash k=new Hash(2);
    map.put(j,1);
    map.put(k,2);



回答2:


The equality check is done by HashMap in three steps:

  1. hash code is different => unequal
  2. objects are identical (==) => equal
  3. equal method gives true => equal

The second step prevents calling equals since identical objects are always assumed equal.




回答3:


From the doc

put(): Associates the specified value with the specified key in this map. If the map previously contained a mapping for this key, the old value is replaced.



来源:https://stackoverflow.com/questions/6641403/java-collections-overriding-equals-and-hashcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!