HashMap 键的迭代顺序是否相同

Iteration Order of HashMap key same or not

我想知道HashMap在每次添加记录后迭代时给出相同序列的键。

我正在使用以下代码

HashMap<String,String> mapObj=new HashMap<String,String>();
mapObj.put("a", "aValue");
mapObj.put("b", "bValue");
mapObj.put("c", "cValue");

for(String key:mapObj.keySet()){
    System.out.println(key+" :: "+mapObj.get(key));
}

for(String key:mapObj.keySet()){
    System.out.println(key+" :: "+mapObj.get(key));
}

以下程序的输出是

b :: bValue  
c :: cValue  
a :: aValue  

b :: bValue  
c :: cValue  
a :: aValue  

如果您在两次迭代之间不对 HashMap 进行任何更改,您可能会看到相同的迭代顺序(即使不能保证),因为这是一个确定性数据结构。但是,在两次迭代之间添加或删除条目可能会改变迭代顺序。

如果您想依赖迭代顺序,请使用 LinkedHashMap,其中(默认情况下)键按照它们首次添加到 Map 的顺序进行迭代。

如果您想以某种特定顺序遍历键,可以改用 TreeMap(其中键根据它们的自然顺序或提供的比较器排序)。

Hash map accept the object to be stored as an argument and generate a number that is unique to it.

HashMap 使用哈希将条目存储在 hashmap 中,因此不能保证这些条目将按特定顺序出现。如果你想从你的 HashMap 中排序你的条目,那么你必须对它进行排序或者你可以使用 Treemap

HashMap 不维持秩序。如果您希望按顺序检索元素,那么最好使用 LinkedHashMap.

通常情况下,如果多次后续调用的迭代顺序发生变化(假设地图本身在这两者之间没有变化),也就不足为奇了。 但是 您不应该依赖它,因为 API 对此不做任何保证。

根据doc

The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.

您可以使用 LinkedHashMap 作为其 entrySet 维护插入顺序,根据 Java Doc:

This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

TreeMap 保持键的自然顺序。

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.