gpt4 book ai didi

Ambiguity during Custom Sorting of TreeMap(树状图自定义排序过程中的歧义)

转载 作者:bug小助手 更新时间:2023-10-26 21:25:20 26 4
gpt4 key购买 nike



the ouptput for the below code is:

以下代码的输出为:


public static void main(String[] args) {
String[] s = {"abc", "def", "ghi"};
TreeMap<String, Integer> tm = new TreeMap<>((a, b) -> -a.length() + b.length());

for (String k : s) {
tm.merge(k, 1, Integer::sum);
}

System.out.println(tm);
}

the output should be:

输出应为:


{abc=1, def=1, ghi=1}

更多回答

"the ouptput for the below code is".... ?

“以下代码的输出为”...?

优秀答案推荐


... the output should be {abc=1, def=1, ghi=1}



There is no reason to expect this behavior. Every comparison operation yields zero (i.e. "equal") for your sample data, and there's no guarantee in the specification (i.e. the Javadoc) that TreeMap preserves insertion order for equal keys. If you want to preserve insertion order you'll need to use a LinkedHashMap.

没有理由期待这种行为。对于样例数据,每个比较操作都会产生零(即“等于”),并且规范(即,Javadoc)中不能保证TreeMap保持相等关键字的插入顺序。如果希望保持插入顺序,则需要使用LinkedHashMap。



The output {abc=3} is not ambigous. You use the custom comparator, that treats all keys with same length as a same keys. And finally, the keys with greater length will be at the beginning.

输出{abc=3}并不含糊。您可以使用定制的比较器,它将所有长度相同的密钥视为相同的密钥。最后,长度较大的密钥将位于开头。


P.S. TreeMap is the Map implementation where keys are unique and sorted with given Comparator.

P.S.treeMap是Map实现,其中键是唯一的,并使用给定的比较器进行排序。


String[] s = { "abc", "def", "ghi", "abc", "def", "abc" };
Map<String, Integer> tm = new TreeMap<>();

for (String k : s) {
tm.merge(k, 1, Integer::sum);
}

System.out.println(tm);

Output:

产出:


{abc=3, def=2, ghi=1}

更多回答

To be more precise, it’s guaranteed that a Map doesn’t store multiple equal keys at all. Since it only keeps the first encountered key, there’s no ordering relationship between equal keys.

更准确地说,可以保证一个映射根本不会存储多个相等的键。因为它只保留第一个遇到的键,所以相等的键之间没有排序关系。

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