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
1 分别:无论您是通过集合还是通过 map 获取对这些对象的引用,在 map 中存储为值的对象状态的自然变化都是可见的;它们是对对象的引用,而不是对象的副本。
关于Java:HashMap类的这个方法是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37840833/