Java集合 - 覆盖equals和hashCode [英] Java collections - overriding equals and hashCode

查看:149
本文介绍了Java集合 - 覆盖equals和hashCode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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());
}
}

输出为

 
内部散列

内部散列
1

因为它返回相同的哈希码,第二次添加一个对象在hashmap它必须使用equals方法,但它不调用。 c> HashMap 正在使用

code> == 之前 .equals ,因为你把同一个对象两次,第一个测试通过。尝试:

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


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?

解决方案

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);

这篇关于Java集合 - 覆盖equals和hashCode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆