我想知道当 HashMap 发生变化时,包含在 HashMap 中的值的 Collection View 是否保持有序。
例如,如果我有一个 HashMap,其 values() 方法返回 L={a, b, c} 如果我向 map 添加一个新元素“d”,L 会发生什么变化? 它是在末尾添加的吗?也就是说,如果我遍历元素,它会保持顺序吗?
特别是,如果添加新元素“d”导致重新散列,顺序会保留在 L 中吗?
非常感谢!
最佳答案
I was wondering if the Collection view of the values contained in a HashMap is kept ordered when the HashMap changes.
不,没有这样的保证。
如果是这种情况,那么下面的程序将输出 1-100 的有序序列
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < 100; i++)
map.put(i, i);
System.out.println(map.values());
( and it doesn't) .
有一个类可以完全满足您的要求,那就是 LinkedHashMap
:
Hash table and linked list implementation of the Map interface, with predictable iteration order. 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).
关于Java HashMap 和底层 values() 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5195845/