Java TreeMap自定义比较器怪异行为 [英] Java TreeMap custom comparator weird behaviour
本文介绍了Java TreeMap自定义比较器怪异行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个具有排序键的 Map
,该键首先按字母顺序排序,最后按数字顺序排序。为此,我使用了 TreeMap
和自定义的 Comparator
:
I am trying to create a Map
with sorted keys, sorted according to alphabetically first, and numerical last. For this I am using a TreeMap
with a custom Comparator
:
public static Comparator<String> ALPHA_THEN_NUMERIC_COMPARATOR =
new Comparator<String> () {
@Override
public int compare(String first, String second) {
if (firstLetterIsDigit(first)) {
return 1;
} else if (firstLetterIsDigit(second)) {
return -1;
}
return first.compareTo(second);
}
};
private static boolean firstLetterIsDigit(String string) {
return (string == null) ? false : Character.isDigit(string.charAt(0));
}
我编写了以下单元测试来说明问题所在:
I've wrote the following unit test to illustrate what goes wrong:
@Test
public void testNumbericallyKeyedEntriesCanBeStored() {
Map<String, String> map = new HashMap<>();
map.put("a", "some");
map.put("0", "thing");
TreeMap<String, String> treeMap = new TreeMap<>(ALPHA_THEN_NUMERIC_COMPARATOR);
treeMap.putAll(map);
assertEquals("some", treeMap.get("a"));
assertEquals("thing", treeMap.get("0"));
}
结果:
java.lang.AssertionError:
Expected :thing
Actual :null
推荐答案
检查比较器代码。比较 0和 0是否应返回0?不,不是这样,因为您不需要检查字符串是否以数字开头。如果两个字符串都以数字开头,那么您也不会返回正确的顺序。
Check your comparator code. Does comparing "0" and "0" return 0, as it should? No it doesn't, since you don't check for equality if your string starts with a digit. You also don't return proper ordering if two strings both start with digits.
这篇关于Java TreeMap自定义比较器怪异行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文