Java: what is the meaning of this method of the HashMap class?

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

Changes made by me to objects in the loop are performed on the same objects on the map?

The manual says this values()method

Gets a view of the collection of values ​​contained in this map. The collection is supported by the map, so changes to the map are reflected in the collection and vice versa.

“Changes in map” mean “changes in mapped objects”? So the method setFieldcan change the objects on the map?

+4
source share
4 answers

“Changes in the map” mean “changes in the displayed objects”?

( . 1). , , ; . :.

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 : , , , , ; , .

+6

HashMap.values() - javadoc.

, . , , . , ( ), undefined. , Iterator.remove, Collection.remove, removeAll, keepAll clear. add addAll.

, ( ) . , , , , , . , .

.

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
}
+1

values ​​ . , , .

0

, :

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

values() : "value1", "value2"

, , values(), . , / .

:

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

:

Before: []
After: [value1]
-1
source

All Articles