hashmap keyset automatically sorted

主宰稳场 提交于 2019-12-10 11:14:15

问题


    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?


回答1:


  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

Source




回答2:


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.



来源:https://stackoverflow.com/questions/17910377/hashmap-keyset-automatically-sorted

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!