0 java collections 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;
}
}
Run Code Online (Sandbox Code Playgroud)
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());
}
}
Run Code Online (Sandbox Code Playgroud)
输出是
inside hash inside hash 1
由于它返回相同的哈希码,第二次在hashmap中添加一个对象时,它必须使用equals方法,但它不会调用.那么问这个问题呢?
在HashMap与测试==之前.equals,因为你是把相同的对象两次,第一次测试通过.试试:
Hash j=new Hash(2);
Hash k=new Hash(2);
map.put(j,1);
map.put(k,2);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1377 次 |
| 最近记录: |