3
    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);
    }

上面的代码日志:

View
Help
File

但是为什么要排序呢?

4

2 回答 2

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

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

资源

于 2013-07-28T16:38:35.757 回答
4

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

于 2013-07-28T16:39:24.823 回答