我有这段代码:
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);
}
对于具有以下对的地图: 2 - UserNotification, 3 - UserNotification, 4 - UserNotification, 5 - UserNotification, 6 - UserNotification, 7 - UserNotification, 8 - UserNotification, 9 - UserNotification, 10 - UserNotification
代码的输出是: 10 2 3 4 五 6 7 8 9
考虑到TreeMap按其键排序所有数据这一事实,这怎么可能?我认为值为10的键应位于列表的末尾。
答案 0 :(得分:6)
TreeMap
正在根据它的键按字典顺序(按字母顺序排序)进行排序,因此任何以1开头的内容都会出现在以等等开头的任何内容之前。
如果您想对地图按数字进行排序,则应该使用TreeMap<Integer, UserNotification>
答案 1 :(得分:3)
您正在使用字符串比较而不是整数。所以“10”在“2”之前。
答案 2 :(得分:3)
这是因为您在密钥集中使用了String
。
因此,Strings
按字典顺序排序,因此10
在2
之前。
使用Integer
s(或Long
s)获得预期的订单。