Jesse
Jesse

Reputation: 1

Java ArrayList of Map - All Map objects are dupe

I have a Map object whose values are constantly changing every time the map is updated. They keys are always the same, but the values change. Every time I change the Map object, I add it to an ArrayList. I can see that the values in the map are different each time the new map is added to the ArrayList, but when the ArrayList finishes being updated and is ready to be read from, all the Map's in it are the same.

Can anyone think of why this might be?

This is basically all that is happening...UpdateLog gets called with a new Map about 20 times and each dataMap1 object is different. It is added to the ArrayList. When I debug, I can see dataMap1 values are different each time. But when it is finished, every dataMap1 object in mapLog is the same!!

public void UpdateLog(final Map<String,String> dataMap1)

{

mapLog.add(dataMap1);    

}

Upvotes: 0

Views: 1218

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502016

You claim each dataMap1 object is different... but don't forget that the value of dataMap1 is just a reference, not an object. If you're doing this:

Map<String, String> map = new HashMap<String, String>();

map.put("a", "b");
UpdateLog(map);

map.clear();
map.put("x", "y");
UpdateLog(map);

then that's not actually using two different objects. Make sure you've really got a different object each time:

// Replaces the call to map.clear()
map = new HashMap<String, String>();
map.put("x", "y");
UpdateLog(map);

If this doesn't help, please post more code. Given your description though, this is what's happening. You may want to copy your map instead of creating a new map each time, of course.

Upvotes: 5

Related Questions