Hi guys

I am facing issue in an array list where i am putting a value at specified index, but it is replacing all the index value in it.
I am putting map inside a arraylist, now in a loop when i am putting value in list.add(i, Map).The value at i as well as all the values in the list gets replace by current value in Map.

So at last i am getting a list containg same map(with the last map value) at all the index.

Please help

Recommended Answers

All 4 Replies

Are you sure you are creating a new map each time?

Keep in mind you're adding a reference to the map, not a snapshot of the map itself. If you change the map the reference in the list will simply point to the changed version.

without seeing the actual code, it's useless to make to much assumptions. usually, problems arise when people think their code should behave in way A, while the code itself (because of a logical error) will behave in way B.

Here is my guess... You did NOT create a new Map object inside your loop but rather replaced the instance's values. Then you added the object to the list. As a results, the list is added with the same reference to the same object in the loop.

You need to recreate the object every time (using new). This is a mistake that those who are new to Java tend to have.

Thanks Taywin, i was making the same mistake.
Thanks Traeval.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.