Java hashmap的自定义键不';行不通
我为hashmap创建了一个自定义密钥类:Java hashmap的自定义键不';行不通,java,hashmap,Java,Hashmap,我为hashmap创建了一个自定义密钥类: package com.amit.test; public class MyCustomKey { int customerId; public MyCustomKey(int customerId){ this.customerId = customerId; } public int getCustomerId() { return customerId; }
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
我希望由于我的key对象包含相同的int值,并且根据我编写的equals方法,它会返回true,那么为什么不将存储为“One”的值替换为“Two”。当我将equals更改为
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MyCustomKey other = (MyCustomKey) obj;
if (this.customerId != other.customerId) {
return false;
}
return true;
}
产量增加了
Custom Key 1 hashCode : 1
Custom Key 2 hashCode : 1
Custom Key 1 equals Key 2 : true
Custom Key 1 == Key 2 : false
Two
在原始代码中,Hashmap使用默认的equals实现,这是由对象类提供的。此equals使用对象的地址,该地址不相等并导致映射中存在两个对象。我想我没有正确重写equals方法。它应该接受一个对象作为参数,并且它应该看起来有点像public boolean equals(Object customKey){if(this==customKey)返回true;if(this.getCustomerId()==((MyCustomKey)customKey.getCustomerId())返回true;返回false;}每当重写方法时,最好使用注释@Override。(例如hasCode和equals方法)如果您的方法签名与来自超类的签名不匹配,编译器将抛出错误。
Custom Key 1 hashCode : 1
Custom Key 2 hashCode : 1
Custom Key 1 equals Key 2 : true
Custom Key 1 == Key 2 : false
Two