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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 17:54:48  来源:igfitidea点击:

hashmap keyset automatically sorted

javahashmap

提问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

  1. HashMap makes absolutely no guarantees about the iteration order. It can (and will) even change completely when new elements are added.

  2. LinkedHashMap will iterate in the order in which the entries were put into the map

  1. HashMap 绝对不保证迭代顺序。当添加新元素时,它甚至可以(并且将会)完全改变。

  2. LinkedHashMap 将按照条目放入地图的顺序进行迭代

Source

来源

回答by NINCOMPOOP

The order in which you see the entries in the HashMapdepends 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 HashMapfor ordering at all. Whereas LinkedHashMapand TreeMapdo guarantee a certain order.

您在 中看到条目的顺序HashMap取决于键的哈希码和存储桶中条目的顺序,我相信它取决于实现,但根本不依赖于HashMap排序。而LinkedHashMapTreeMap确实保证一定的顺序。