Java:HashMap类的这个方法是什么意思?

标签 java dictionary

class MyObject {
    int field;
    public void setField(int arg1) { 
        this.field = arg1;
    }
} 

HashMap<String, MyObject> map;
... 
... // put some MyObjects in the map with strings as keys
...
for (MyObject object : map.values()) {
    object.setField(12345);
}

我在循环中对对象所做的更改是在 map 中的相同对象上进行的?

指南是关于 values() 方法的:

Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa.

“对 map 的更改”是否意味着“对映射对象的更改”?那么这样setField方法就可以改变 map 中的对象了?

最佳答案

Does "changes to the map" mean "changes to the mapped objects"?

这意味着对 map 的更改(但也请参阅下面的1)。该集合是映射中值的实时 View ,因此当您向映射添加条目或从映射中删除条目时,集合会反射(reflect)这些更改;两者是联系在一起的。例如:

Map<String, String> m = new HashMap<String, String>();
Collection<String> c = m.values();
m.put("hi, "there");
System.out.println(c.size()); // 1, not 0

Live Example


1 分别:无论您是通过集合还是通过 map 获取对这些对象的引用,在 map 中存储为值的对象状态的自然变化都是可见的;它们是对对象的引用,而不是对象的副本

关于Java:HashMap类的这个方法是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37840833/

相关文章:

Java WebSockets : The remote endpoint was in state [TEXT_FULL_WRITING]

c# - 使用 linq 将列表转换为字典而不用担心重复

java - 制作正确的二叉树

c# - 如何序列化具有 Dictionary<string,object> 属性的对象?

python - 同时操作字典中键的两个值

python - 为什么 Python 2.7 中的 dict 定义比 Python 3.x 中的更快?

python - configparser 中的多维字典

java - 为什么我的 Minecraft bukkit 插件出现 mysql 延迟?

java - 如何在 JavaFX 中调用场景最大化(而不是调整大小)函数

java.lang.illegalstateException 应用程序未正确初始化