如何维护插入顺序

sar*_*rah 27 java collections dictionary

我想将一个键值对添加到哈希表(或任何其他集合)中,但必须维护插入顺序.我怎样才能做到这一点?

就像我将1添加为键"一"作为值,2作为键和"两"作为值.

输出应该是:

1:one
2:two
Run Code Online (Sandbox Code Playgroud)

pol*_*nts 60

以下是一些重要Map实现的特征差异:

  • LinkedHashMap:"具有可预测的迭代顺序[...],通常是键插入映射的顺序(插入顺序)."
  • HashMap:"不保证地图的顺序"
  • TreeMap:"根据其键的自然顺序排序,或者按Comparator"

所以LinkedHashMap在这种情况下看起来就像你需要的那样.

这是一个说明差异的片段; 它还显示了迭代a的所有条目的常用方法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());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

以上代码段的输出(如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
Run Code Online (Sandbox Code Playgroud)

相关问题

类似的问题


Pet*_*aný 11

对于哈希表,请使用LinkedHashMap类.