有序地图实施

Dón*_*nal 5 java collections

我正在寻找一个Map实现,它按照添加顺序迭代键值对.例如

Map orderedMap = // instantiation omitted for obvious reasons :)
orderMap.put(4, "d");
orderMap.put(10, "y");
orderMap.put(2, "b");

for (Map.Entry entry : orderedMap.entrySet()) {
  System.out.println(entry.getKey() + ", " + entry.getValue());
}
Run Code Online (Sandbox Code Playgroud)

将永远打印

4, d
10, y
2, b
Run Code Online (Sandbox Code Playgroud)

我正在使用Java 5.0.

谢谢,唐

unb*_*eli 9

这是LinkedHashMap

  • 并且为了完整起见,JDK中另一个有趣的Map实现是TreeMap,它将按排序顺序返回键(在您的情况下为2,4,10). (2认同)