Java 如果键字段是类的实例,如何更新HashMap中的值?

Java 如果键字段是类的实例,如何更新HashMap中的值?,java,hashmap,Java,Hashmap,假设我有一个代码片段: package practice; import java.util.*; public class Practice { public static void main(String[] args) { Map<Temp,Integer> m = new HashMap<>(); m.put(new Temp(1,2), 5); m.put(new Temp(1,2), 6);

假设我有一个代码片段:

package practice;
import java.util.*;

public class Practice {
    public static void main(String[] args) {
        Map<Temp,Integer> m = new HashMap<>();
        m.put(new Temp(1,2), 5);
        m.put(new Temp(1,2), 6);
        System.out.println(m.size());
    }
}

class Temp {
    int x, y;
    public Temp(int a, int b) {
        this.x = a;
        this.y = b;
    }
}
包装实践;
导入java.util.*;
公共课堂实践{
公共静态void main(字符串[]args){
Map m=新的HashMap();
m、 放置(新温度(1,2,5);
m、 放置(新温度(1,2,6);
System.out.println(m.size());
}
}
班级临时工{
int x,y;
公共温度(内部a、内部b){
这个x=a;
这个y=b;
}
}
输出:
2


我正在尝试更新与对象
new Temp(1,2)
对应的值,但它正在插入而不是替换它。这就是为什么大小为
2
。如何替换旧值?

Java默认情况下比较引用,除非实现
equals
hashCode
方法:

class Temp {
    // ...

    public boolean equals(Object obj) {
        Temp temp = (Temp)obj;
        return temp.x == this.x && temp.y == this.y;
    }

    public int hashCode() {
        return Objects.hash(this.x, this.y);
    }
}
然后:

注意
Temp=(Temp)objobj
不是
Temp
的insance,则code>将抛出
ClassCastException
。它应该返回
false
System.out.println(m.size()); // 1