Map<String, String> map = new HashMap<String, String>();
for (int i=0; i<5; i++) {
map.put("key"+i, "value" + i);
}
for (Map.Entry<String, String> item : map.entrySet()) {
System.out.println(item.getKey() + "==" + item.getValue());
}
打印:顺序错乱
key1==value1
key2==value2
key0==value0
key3==value3
key4==value4
需要使用LinkedHashMap
Map<String, String> map = new LinkedHashMap<String, String>();
for (int i=0; i<5; i++) {
map.put("key"+i, "value" + i);
}
for (Map.Entry<String, String> item : map.entrySet()) {
System.out.println(item.getKey() + "==" + item.getValue());
}
打印:
key0==value0
key1==value1
key2==value2
key3==value3
key4==value4
原因:LinkedHashmap 的特点是put进去的对象位置未发生变化,而HashMap会发生变化。