开发者

Java ArrayList of Map - All Map objects are dupe

开发者 https://www.devze.com 2023-02-19 23:31 出处:网络
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 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 dif开发者_运维知识库ferent. 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);    

}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消