简体   繁体   中英

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?

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. Eg:

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.

The method HashMap.values() - as described in the javadoc.

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. If the map is modified while an iteration over the collection is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

What this is saying is it returns a collection (similar to a List) of all the elements in the array. It also states that the collection is backed by the map, so if you change the map, the collection will also update, and changing the collection will also change the map. Note that it is impossible to add elements from this collection.

This example shows the use of the method quite well.

public static void main(String[] args) {
    Map<String, String> mapValues = new HashMap<>();
    mapValues.put("Hi", "Hello");
    mapValues.put("Bye", "Goodbye");
    System.out.println(mapValues.size());//prints 2
    Collection<String> values = mapValues.values();
    values.remove("Hello");
    System.out.println(mapValues.size());//prints 1
    System.out.println(values.size());//prints 1
    mapValues.put("Morning", "Good morning");
    System.out.println(mapValues.size());//prints 2
    System.out.println(values.size());//prints 2
}

The values method returns a set of references to your objects in memory. Since your objects are mutable, any changes made to them will be reflected in the map, since the map has references to the same memory.

An example for Map that contains:

"key1" -> "value1"
"key2" -> "value2"

values() will return a collection of: "value1", "value2"

And yes, if you use a mutating method on an object in the map it will change in the values() collection that you retrieved previously. But the most interesting part is that adding/removing elements from map will cause the values collection to change .

Example:

Map<String, String> map = new HashMap<>();
Collection<String> vals = map.values();
System.out.println("Before: " + vals);
map.put("key1", "value1");
System.out.println("After: " + vals);

This will print:

Before: []
After: [value1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM