【发布时间】:2011-02-27 18:15:38
【问题描述】:
我想将键、值对添加到哈希表(或任何其他集合)中,但必须保持插入顺序。我该怎么做?
就像我将添加 1 作为键“一”作为值,2 作为键和“二”作为值。
输出应该是:
1:one
2:two
【问题讨论】:
标签: java dictionary collections
我想将键、值对添加到哈希表(或任何其他集合)中,但必须保持插入顺序。我该怎么做?
就像我将添加 1 作为键“一”作为值,2 作为键和“二”作为值。
输出应该是:
1:one
2:two
【问题讨论】:
标签: java dictionary collections
以下是一些重要的Map 实现的特征差异:
LinkedHashMap:“具有可预测的迭代顺序 [...],这通常是键插入映射的顺序 (insertion-order)。”HashMap: "不保证地图的顺序"TreeMap:“根据其键的自然顺序排序,或按Comparator”
SortedMap
所以看起来LinkedHashMap 是您在这种情况下所需要的。
这里有一个 sn-p 来说明差异;它还展示了一种迭代 Map 的所有条目的常用方法,以及如何使用接口来引用对象允许选择实现的极大灵活性。
import java.util.*;
public class MapExample {
public static void main(String[] args) {
populateThenDump(new HashMap<String,Integer>());
populateThenDump(new TreeMap<String,Integer>());
populateThenDump(new LinkedHashMap<String,Integer>());
}
static void populateThenDump(Map<String,Integer> map) {
System.out.println(map.getClass().getName());
map.put("Zero", 0);
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
map.put("Four", 4);
for (Map.Entry<String,Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}
}
}
上面sn-p的输出是(as seen on ideone.com):
java.util.HashMap // unordered, results may vary
Three => 3
Zero => 0
One => 1
Four => 4
Two => 2
java.util.TreeMap // ordered by String keys lexicographically
Four => 4
One => 1
Three => 3
Two => 2
Zero => 0
java.util.LinkedHashMap // insertion order
Zero => 0
One => 1
Two => 2
Three => 3
Four => 4
Iterator。【讨论】:
对于哈希表,使用LinkedHashMap 类。
【讨论】:
您正在搜索LinkedHashMap 类。
【讨论】: