散列映射的自定义键不起作用

时间:2016-04-13 16:51:10

标签: java hashmap

我为我的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,那么为什么不用'Two'替换存储为'One'的值

0 个答案:

没有答案