如何确保在Java中遍历HashMap时无法更改密钥的顺序?

How to make sure the key's order can not be changed when traversing a HashMap in Java?

本问题已经有最佳答案,请猛点这里访问。

例如,我输入3个字符串:Hagzou Hugzou Jigxng作为HashMap的键,

但是当我按键遍历HashMap时,订单已被更改:Hugzou Hagzou Jigxng。

是否可以确保在输出密钥时无法更改订单?

像这样:

输入:Hagzou Hugzou Jigxng ###

输出:Hagzou Hugzou Jigxng

多谢!

这是我的代码:

1
2
3
4
5
6
7
8
9
10
11
    HashMap< String, Integer > distance = new HashMap< String, Integer >();
    Scanner input = new Scanner(System.in);    
    while (true) {
        String city = input.next();
        if (city.equals("###"))
            break;
        distance.put(city, null);
    }
    for (String city : distance.keySet()) {
        System.out.println(city);
    }


您可以使用LinkedHashMap

Hash table and linked list implementation of the Map interface, with
predictable iteration order. This implementation differs from HashMap
in that it maintains a doubly-linked list running through all of its
entries. This linked list defines the iteration ordering, which is
normally the order in which keys were inserted into the map
(insertion-order). Note that insertion order is not affected if a key
is re-inserted into the map. (A key k is reinserted into a map m if
m.put(k, v) is invoked when m.containsKey(k) would return true
immediately prior to the invocation.)

换句话说 - 虽然LinkedHashMap有一种通过其哈希码访问条目的方法,如常规HashMap,它还维护一个双向链表,并维护项插入的顺序。 这样,当您使用其迭代器时,您将按照插入它们的顺序获取项目。