user3290180 user3290180 - 5 months ago 22
Java Question

Java: what's the meaning of this method of class HashMap?

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);
}


The changes I made to objects within the cycle are made on the same objects in the map?

The guide says this about the
values()
method


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.


Does "changes to the map" mean "changes to the mapped objects"? So this way the
setField
method can change the objects in the map?

Answer

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

It means changes to the map (but see also 1 below). The collection is a live view of the values in the map, so as you add entries to the map or remove entries from the map, the collection reflects those changes; the two are linked. E.g.:

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 Separately: Naturally changes to the state of objects stored as values in the map will be visible regardless of whether you get the reference to those objects via the collection or the map; they're references to the objects, not copies of the objects.