user3290180 user3290180 - 1 year ago 90
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()) {

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

The guide says this about the

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
method can change the objects in the map?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download