anuone可以解释以下代码如何工作吗?

时间:2019-07-10 09:59:06

标签: java object hashmap

我有一个自定义类,该类已覆盖hashcode()equals()方法

class Employee1{
private int id;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public Employee1(int id) {
    super();
    this.id = id;
}
@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + id;
    return result;
}
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Employee1 other = (Employee1) obj;
    if (id != other.id)
        return false;

    return true;
}

}

在主类中,我使用的是MapObject的{​​{1}}

Key

我的问题是,即使我重写了Map<Integer,Employee1> g = new HashMap<>(); Employee1 e = new Employee1(1); Employee1 e1 = new Employee1(2); g.put(1, e); g.put(2, e1); Employee1 e4 = g.get(1); e4.setId(3); for(Map.Entry<Integer,Employee1> e3:g.entrySet()) { System.out.println(e3.getKey()+" "+e3.getValue().getId()); } hashcode方法,地图的键又如何变化,键应该是相同的,但是我能够获取并设置id及其反映在equals

以上代码的o / p为

1 3 2 2

2 个答案:

答案 0 :(得分:0)

方法var x = ["A", "B", "C"]; console.log(x.map(obj => {return {name: obj}}));equals()用于hashCode()中的键,而不用于值。要查看差异,您可以尝试将类HashMap用作Employee1中的值,或者仅使用Map,它在幕后使用HashSet<Employee1>

答案 1 :(得分:0)

“地图的键如何更改” -它不会更改,因为您可以看到输出中的1和2就是您原来的样子在 androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.2.0' androidTestImplementation 'androidx.test.espresso:espresso-intents:3.2.0' androidTestImplementation 'androidx.test.espresso:espresso-accessibility:3.2.0' androidTestImplementation 'androidx.test.espresso:espresso-web:3.2.0' androidTestImplementation 'androidx.test.espresso.idling:idling-concurrent:3.2.0' implementation 'androidx.test.espresso:espresso-idling-resource:3.2.0' androidTestImplementation 'androidx.test:runner:1.2.0' androidTestImplementation 'androidx.test:rules:1.2.0' androidTestImplementation 'androidx.test.ext:junit:1.1.1' debugImplementation 'androidx.fragment:fragment-testing:1.2.0-alpha01' implementation 'androidx.fragment:fragment:1.2.0-alpha01' androidTestImplementation 'org.mockito:mockito-android:2.24.5' 中使用。

您可以更改的是地图内对象所指向的内容,即值。当您将地图放入地图时,地图不会复制put,它会保留对您称为Employee1的同一实例的引用。如果您从地图e获得该值,则现在与e4完全相同。

Is Java “pass-by-reference” or “pass-by-value”?可能对您有所帮助。

从不不应该做的事情就是使e计算中涉及的某些事物发生突变(如果有人真的依赖哈希码)。因为在更改之后,对象的哈希码更改了,所以HashMap(或HashSet)看不到更改,因为它没有重新计算哈希码的原因,因为它无法得知您对某些内容进行了突变(相关)。