Java HashMap 和底层 values() 集合

标签 java hashmap

我想知道当 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/

相关文章:

java - 无效 key 异常 :Ilegal key size

java - emr如何在用户定义的函数中访问aws凭证

java - 如何为android中的字符串输入生成唯一的哈希码...?

java - 从针对 List<String> 的嵌套 HashMap<String, HashMap<String, String>> 过滤器获取 HashMap 值

jsp - 在 JSP 中通过变量访问 hashmap 值

java - 抓取 key 为某个值的对象

java - Eclipse 指向依赖项中的错误路径

java - 关于 Java 中静态字符串与看似本地字符串的生命周期

java - 在 Spring Security 中使用个人资料名称或电子邮件登录

Java反射方法hashmap