java 按已设置的顺序迭代 HashMap
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13893794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterating HashMap on order it has been set
提问by AHHP
I've set a HashMap on certain order but it is iterated on a strange order!
我已经按特定顺序设置了 HashMap,但它以奇怪的顺序迭代!
Please consider code below:
请考虑以下代码:
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));
}
and the result:
结果:
Name: the name
Sort: the sort
Type: the type
ID: 1
I need to iterate it in order i've put the entries. Any help will be appreciated.
我需要迭代它才能放置条目。任何帮助将不胜感激。
回答by Tomasz Nurkiewicz
That's how HashMap
works internally. Replace HashMap
with LinkedHashMap
which additionally remembers the order of insertion:
这就是HashMap
内部运作的方式。替换HashMap
为LinkedHashMap
另外记住插入顺序:
Map<String, String> map = new LinkedHashMap<String, String>();
回答by Miquel
The order depends on the result of the hashCode()
function in the keys you are inserting which, unless you did something strange, is going to be mostly random (but consistent). What you are looking for is a sorted map such as a LinkedHashMap
顺序取决于hashCode()
您插入的键中函数的结果,除非您做了一些奇怪的事情,否则将主要是随机的(但一致)。您正在寻找的是一个排序的映射,例如LinkedHashMap
Check out a little bit about how hashtableswork here if you are interested in the details.
如果您对详细信息感兴趣,请在此处查看有关哈希表如何工作的一些信息。