0

If i create a class that has a member variable called "testName", and then create a few objects from this and place them all as values in a "Map". How can i iterate through this Map and modify the "testName" variable in each value Object?

In other words how can i access & modify members of an Object when that object has been placed in a Map.

RealHowTo
  • 34,977
  • 11
  • 70
  • 85
alius
  • 15
  • 3

3 Answers3

2

You have to iterate through each of the entries of the Map and modify the name. See here for example on how to iterate through the Map

Aravind Yarram
  • 78,777
  • 46
  • 231
  • 327
2

If the objects you want modified are all values in the map, and you don't want to change the mappings from key to value, you can iterate through a collection of just the map's values:

Collection< ValueType > vals = map.values();
for (ValueType val : vals) {
    val.testName = ...
}
robert_x44
  • 9,224
  • 1
  • 32
  • 37
  • This put me in the right direction. i have also discovered that you can apparently modify members by doing: testmap.get("foo").testName = "new value"; – alius Jan 17 '11 at 03:15
1

A Map is not by itself iterable, but you can get the keySet from the map via the keySet() method and since this is a Set is iterable (implements the Iterable interface). Iterate through the keySet obtaining each value from the Map via its get method and make the changes you desire.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373