【问题标题】:Modify existing Key of HashMap In Java修改Java中HashMap的现有Key
【发布时间】:2018-02-23 05:47:08
【问题描述】:

几天以来我一直在使用 HashMap,并且面临以下奇怪的情况。

Case 1:Changed Key 已经存在于HashMap中,并打印HashMap 情况 2:更改了 HashMap 中已经存在的键,并将该键再次放入 HashMap。打印 HashMap。

请找到下面的代码以及两个案例的两个不同输出。

请任何人告诉我,下面的代码发生了什么。

import java.util.HashMap;
import java.util.Set;

class Emp{
    private String id ;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public Emp(String id) {
        super();
        this.id = id;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Emp other = (Emp) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }
    @Override
    public String toString() {
        return "Emp [id=" + id + "]";
    }

}
public class HashMapChanges {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Emp e1 = new Emp("1");
        Emp e2 = new Emp("2");
        Emp e3 = new Emp("3");
        Emp e4 = new Emp("4");

        HashMap<Emp, String> hm = new HashMap<Emp,String>();

        hm.put(e1,"One");
        hm.put(e2,"Two");
        hm.put(e3,"Three");
        hm.put(e4,"Four");

        e1.setId("5");

        /** Uncomment below line to get different output**/
        //hm.put(e1,"Five-5");

        Set<Emp> setEmpValue = hm.keySet();
        for(Emp e : setEmpValue){
            System.out.println("Key"+ e +" Value "+ hm.get(e));
        }
    }
}

以上代码的输出:

KeyEmp [id=2] Value Two  
KeyEmp [id=5] Value null  
KeyEmp [id=4] Value Four  
KeyEmp [id=3] Value Three

取消注释后的输出

KeyEmp [id=5] Value Five-5  
KeyEmp [id=2] Value Two  
KeyEmp [id=5] Value Five-5  
KeyEmp [id=4] Value Four  
KeyEmp [id=3] Value Three

【问题讨论】:

    标签: java hashmap


    【解决方案1】:

    当用于确定其在 Map 中位置的键是可变的时,不允许在 Map 中使用可变对象作为键。

    来自java.util.Map&lt;K,V&gt; 的 Javadoc:

    注意:如果将可变对象用作映射键,则必须非常小心。如果对象的值以影响等于比较的方式更改,而对象是映射中的键,则不指定映射的行为。

    您违反了映射键所需的约定,因为您的 Emp 对象是可变的,并且更改修改了用于确定键驻留在映射中的位置的属性。

    结果是未定义的行为。

    我怀疑您根据您的代码误解了Map 的概念,但如果不了解您实际想要实现的目标,我们真的无法提供进一步的帮助。我建议你问一个新问题来解释你的实际目标。

    【讨论】:

      【解决方案2】:

      您覆盖了hashCode()equals() 方法, 那么,Map 的 key 就是 hashCode 结果。 那么id=1id=5 是两个不同的项目。

      你可以评论这两种方法,然后再试一次。

      【讨论】:

        猜你喜欢
        • 2020-10-19
        • 1970-01-01
        • 1970-01-01
        • 2012-08-13
        • 2020-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-11
        相关资源
        最近更新 更多