为什么我的 TreeMap 没有排序?

Why is my TreeMap not sorting?

我使用了 TreeMap,其中键是 String,值是 Integer 类型。当我输出 Map 对象时,它没有按排序顺序打印。

这是我使用的代码:

TreeMap<String, Integer> m = new TreeMap<String, Integer>();
m.put("Hello", 1);
m.put("world", 2);
m.put("Zertt", 5);
m.put("Hello", 1);
m.put("world", 2);
System.out.println("map : " + m);

我希望输出像这样排序:

map : {Hello=1, world=2, Zertt=5}

但我却得到了这个:

map : {Hello=1, Zertt=5, world=2}

Strings 的自然顺序区分大小写,因此 Zw 之前(所有大写字母都在所有小写字母之前)。

使用

TreeMap<String, Integer> m = new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER);

不区分大小写的顺序。

树图中的排序是基于键的自然顺序而不是值。

Javadoc 说:

The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

编辑:Eran 的回答是正确的,字符串排序默认区分大小写。

如前所述,字符串自然顺序区分大小写。但是,如果你想要不敏感的排序,你可以提供比较器作为 TreeMap 构造函数参数:

Map<String, Integer> m = new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER);

p.s。请注意,当使用不区分大小写的顺序键时,也会比较不区分大小写:

m.put("Hello", 1);
m.put("helLo", 6);

结果为 6,密钥为 Hello

也许这些信息会有帮助。

In the class TreeMap contains constructors:

  1. TreeMap ()

  2. TreeMap (Comparator comp)

  3. TreeMap (Map m)

  4. TreeMap (SortedMap sm)

The first constructor creates a collection in which all the elements are sorted in natural order of their keys.

The second constructor creates an empty collection, the elements of which will be sorted according to the law, which is defined in the transmission comparator.

The third constructor creates a TreeMap based on an existing Map.

The fourth constructor creates a TreeMap based on existing SortedMap, elements of which will be sorted according to the law transmitted SortedMap.

Note that keys used for the sorting, rather than the value.