gpt4 book ai didi

java - TreeMap put 未按预期工作

转载 作者:搜寻专家 更新时间:2023-10-31 08:09:43 25 4
gpt4 key购买 nike

class Point{
int x, y, l;

Point(int x, int y, int l){
this.x =x;
this.y =y;
this.l=l;
}
@Override
public int hashCode() {
return y;
}

@Override
public boolean equals(final Object obj) {
if(this == obj) return true;
if(!(obj instanceof Point)) return false;
Point p = (Point) obj;
return this.x == p.x && this.y == p.y;
}
}

TreeMap<Point,Integer> sortedMap = new TreeMap<>((p1, p2)-> p1.l-p2.l);
sortedMap.put(new Point(4,5,0),0);
sortedMap.put(new Point(5,5,0),6);
System.out.println(sortedMap.size()); -> Output: 1
System.out.println((new Point(4,5,0)).equals(new Point(5,5,0))); -> Output -> False.

我在类中重载了 hashcode 和 equals 方法。我认为put方法应该使用equals方法来判断同一个对象是否存在。但它没有按预期工作。

我不确定为什么我的 hashMap 大小为 1。 如果我理解 hashmap 工作有误,请告诉我。帮我找出这段代码中的错误?

最佳答案

您的 TreeMap 正在比较 l 部分的 Point 值(无论这意味着什么)。这就是这部分代码的作用:

new TreeMap<>((p1, p2)-> p1.l-p2.l);

您创建的两个点具有相同的 l 值 (0),因此它们被认为是相等的...因此第二次调用 put 会替换现有的入口。 TreeMap 根本不使用 equalshashCode

来自documentation :

Note that the ordering maintained by a tree map, like any sorted map, and whether or not an explicit comparator is provided, must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.

您的比较equals 一致,这就是您看到违反Map 协定的结果的原因。

关于java - TreeMap put 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45438097/

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