我有这段代码:
private final static TreeMap<String, UserNotification> USER_NOTIFICATION_MAP = new TreeMap<String, UserNotification>();
//Filling the map using services
String idString = "1";
Iterator it = USER_NOTIFICATION_MAP.entrySet().iterator();
while (it.hasNext())
{
Map.Entry pairs = (Map.Entry)it.next();
idString = pairs.getKey().toString();
System.out.println(idString);
}
对于具有以下对的 Map :2 - UserNotification,3 - UserNotification,4 - UserNotification,5 - UserNotification,6 - UserNotification,7 - UserNotification,8 - UserNotification,9 - UserNotification,10 - UserNotification
代码输出为:10 2 3 4 5 6 7 8 9
考虑到TreeMap按键对所有数据进行排序,这怎么可能呢?我想值10的键应该在列表的末尾 .
3 回答
TreeMap
正在按字典顺序(按字母顺序)对其键进行排序,所以以1开头的任何内容都以2开头的任何内容开头 .如果你想用数字排序你的 Map ,你应该使用
TreeMap<Integer, UserNotification>
您正在使用字符串比较而不是整数 . 所以“10”在“2”之前 .
发生这种情况是因为您在密钥集中使用了
String
.因此,
Strings
按字典顺序排序,因此10
在2
之前 .使用
Integer
s(或Long
s)来获得预期的订单 .