-5

I have problem with this code,when I add map object to list,all previous added object will be changed.how can I declare map as non static?

for(Statment){
   map.put(Key,value),                 
 }            
 result.add(map);
Arash K
  • 13
  • 1
  • 8

3 Answers3

1

When you add something to a container, you are adding the reference (not a copy of the object it references) If you want to add a copy (so that if you can change the original, and the copy added to the list does not change) you have to explicitly copy it.

e.g.

Map<Integer, Integer> map = new LinkedHashMap<Integer, Integer>();
for(int i=0;i<10;i++)
   map.put(i, i);
list.add(new LinkedHashMap<Integer, Integer>(map)); // add a copy.
// you can change map without the list changing as well.
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

Try this.

for (condition) {
   if (!map.containskey(key)) {
       map.put(key,value);
   }                 
}            
result.add(map);
Vaandu
  • 4,857
  • 12
  • 49
  • 75
0

You have to declare each object outside the for otherwise you are adding just one reference, and any modification modifies all.

ssedano
  • 8,322
  • 9
  • 60
  • 98