java hashmap 键集自动排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17910377/
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
hashmap keyset automatically sorted
提问by Jochem Gruter
HashMap<String, String[]> content = new HashMap<String, String[]>();
content.put("Help", new String[]{"About"});
content.put("View", new String[]{"Grid"});
content.put("File", new String[]{"Import", "Export"});
for(String key : content.keySet()){
System.out.println(key);
}
The above code logs:
上面的代码日志:
View
Help
File
But why is this sorted?
但为什么要这样排序?
回答by Boris Mocialov
回答by NINCOMPOOP
The order in which you see the entries in the HashMap
depends on the hash codes of the keys and order of the entries in the bucket I believe and it is implementation dependent, but don't rely on HashMap
for ordering at all. Whereas LinkedHashMap
and TreeMap
do guarantee a certain order.
您在 中看到条目的顺序HashMap
取决于键的哈希码和存储桶中条目的顺序,我相信它取决于实现,但根本不依赖于HashMap
排序。而LinkedHashMap
并TreeMap
确实保证一定的顺序。