按顺序迭代HashMap已设置

AHH*_*HHP 16 java iteration hashmap

我已经按特定顺序设置了HashMap,但它是在一个奇怪的顺序上迭代的!

请考虑以下代码:

HashMap<String, String> map = new HashMap<String, String>();
map.put("ID", "1");
map.put("Name", "the name");
map.put("Sort", "the sort");
map.put("Type", "the type");

...

for (String key : map.keySet()) {
    System.out.println(key + ": " + map.get(key));
}
Run Code Online (Sandbox Code Playgroud)

结果:

Name: the name
Sort: the sort
Type: the type
ID: 1
Run Code Online (Sandbox Code Playgroud)

我需要迭代它以便我输入条目.任何帮助将不胜感激.

Tom*_*icz 28

这就是HashMap内部运作的方式.替换HashMapLinkedHashMap另外记住插入顺序:

Map<String, String> map = new LinkedHashMap<String, String>();
Run Code Online (Sandbox Code Playgroud)


Miq*_*uel 25

顺序取决于hashCode()你插入的键中函数的结果,除非你做了一些奇怪的事情,否则它将主要是随机的(但是一致的).您正在寻找的是一个有序的地图,如LinkedHashMap

如果您对细节感兴趣,请查看一下哈希表如何在这里工作.