【发布时间】:2016-04-13 16:51:10
【问题描述】:
我已经为我的 hashmap 制作了一个自定义键类:
package com.amit.test;
public class MyCustomKey {
int customerId;
public MyCustomKey(int customerId){
this.customerId = customerId;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public int hashCode(){
//return Double.valueOf(Math.random()).intValue() * customerId;
return customerId;
}
public boolean equals(MyCustomKey customKey){
if(this == customKey)
return true;
if(this.getCustomerId() == customKey.getCustomerId())
return true;
return false;
}
}
然后我在主类中使用如下:
package com.amit.test;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MyCustomHashMap {
public static void main(String[] args) {
Map<MyCustomKey, String> map = new HashMap<MyCustomKey, String>();
MyCustomKey customKey1 = new MyCustomKey(1);
System.out.println("Custom Key 1 hashCode : " + customKey1.hashCode());
MyCustomKey customKey2 = new MyCustomKey(1);
System.out.println("Custom Key 2 hashCode : " + customKey2.hashCode());
System.out.println("Custom Key 1 equals Key 2 : " + customKey1.equals(customKey2));
System.out.println("Custom Key 1 == Key 2 : " + (customKey1 == customKey2));
map.put(customKey1, "One");
map.put(customKey2, "Two");
Set<MyCustomKey> keys = map.keySet();
for(MyCustomKey key : keys){
System.out.println(map.get(key));
}
}
}
输出::
我想知道为什么我得到的输出为:
Custom Key 1 hashCode : 1
Custom Key 2 hashCode : 1
Custom Key 1 equals Key 2 : true
Custom Key 1 == Key 2 : false
One
Two
而不是:
Custom Key 1 hashCode : 1
Custom Key 2 hashCode : 1
Custom Key 1 equals Key 2 : true
Custom Key 1 == Key 2 : false
One
我希望由于我的键对象包含相同的 int 值,并且根据我编写的 equals 方法,它返回 true,那么它为什么不将存储为 'One' 的值替换为 'Two' .
【问题讨论】:
-
我想我没有正确覆盖 equals 方法。它应该接受一个对象作为参数,它应该有点像 public boolean equals(Object customKey){ if(this == customKey) return true; if(this.getCustomerId() == ((MyCustomKey)customKey).getCustomerId()) 返回真;返回假; }
-
在重写方法时使用注释@Override 是一种很好的做法。 (例如 hasCode 和 equals 方法)如果您的方法签名与超类的签名不匹配,编译器将抛出错误。