gpt4 book ai didi

java - 我的树形图在排序后中断,因为 "comparator used for the treemap is inconsistent with equals"

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

我需要根据树形图的值对其进行排序。我正在做的事情的要求是我必须使用排序的 map 。我在这里尝试了解决方案:Sort a Map<Key, Value> by values (Java)然而,正如评论所说,这将使从我的 map 获取值不起作用。因此,我执行了以下操作:

class sorter implements Comparator<String> {
Map<String, Integer> _referenceMap;
public boolean sortDone = false;
public sorter(Map<String, Integer> referenceMap) {
_referenceMap = referenceMap;
}
public int compare(String a, String b) {
return sortDone ? a.compareTo(b) : _referenceMap.get(a) >= _referenceMap.get(b) ? -1 : 1;
}
}

因此,我将 sortDone 保留为 false,直到完成对 map 的排序,然后将 sortDone 切换为 true,以便它可以正常比较事物。问题是,我仍然无法从 map 上获取元素。当我执行 myMap.get(/anything/) 时,它始终为 null 。

我也不明白与 equals Even 不一致的比较器是什么意思。

最佳答案

I also do not understand what the comparator inconsistent with equals even means.

根据 contract of the Comparable interface .

The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C. Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.

It is strongly recommended (though not required) that natural orderings be consistent with equals.

我相信你需要更改线路:

 _referenceMap.get(a) >= _referenceMap.get(b) ? -1 : 1;

 _referenceMap.get(a).compareTo(_referenceMap.get(b));

因为如果 _referenceMap.get(a) 返回的 Integer 实际上是 ==Integer 值code> 由 _referenceMap.get(b) 返回,那么理想情况下您应该返回 0,而不是 -1

关于java - 我的树形图在排序后中断,因为 "comparator used for the treemap is inconsistent with equals",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17961762/

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