0

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

}

0

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

12 Comments

Skeet is going to publish a book of all his SO answers and retire. Then we can finally get some reputation.
@Jon Skeet - the thing is, the thread that updates dataMap nulls it out every time...while (!stop && serviceCn.isRunning()) { MyService svc = myServiceConn.getService(); Map<String,String> dataMap = null; dataMap = svc.getDataMap(); UpdateLog(dataMap) }
@Jesse: Setting it to null is pointless when you're about to assign the variable based on a call to svc.getDataMap() in the following statement. My guess is that svc.getDataMap() is returning a reference to the same map every time. That's what you need to look into.
sorry i just joined stackoverflow and when i try to add a comment i dont know how to designate it as code block and when i hit enter it just adds the comment :/
@Jesse: Just include it in backticks, so backtick x backtick becomes x.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.