gpt4 book ai didi

java - 为什么覆盖 equals 不适用于在 Map 中添加相同的对象?

转载 作者:行者123 更新时间:2023-12-01 06:01:14 25 4
gpt4 key购买 nike

如果你看一下这个程序,在 Location 类中,我们重写了两个方法(equals 和 hashcode),分别返回 false 和 110。我们正在创建 Location 类的一个实例,并放入 map 两次。当我们从 equals 方法返回 false 时,为什么映射会用 key 覆盖最后一个值?

class Location {

long latitude;
long longitude;

public Location(long latitude,int longitude) {
this.latitude = latitude;
this.longitude = longitude;
}

@Override
public boolean equals(Object obj) {
return false;
}

@Override
public int hashCode() {
return 110;
}

@Override
public String toString() {
return String.format("Latitude := %d , Longitude :=%d ", latitude,longitude);
}

}

Map<Location, String> locations = new HashMap<>();

Location l1 = new Location(2,3);
locations.put(l1, "Mumbai");
locations.put(l1,"Pune");

System.out.println(locations+ " with size of :"+locations.size());

最佳答案

我查看了 HashMap 实现。显然,您的 Location::equals 从未被调用,因为 == 用于测试键的相等性。
其原因是 – 感谢 chrylis – 您添加了相同的位置两次。
更改您的代码:

Location l1 = new Location( 2, 3 );
locations.put( l1, "Mumbai" );

Location l2 = new Location( 2, 3 );
locations.put( l2, "Pune" );

关于java - 为什么覆盖 equals 不适用于在 Map 中添加相同的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58144189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com