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);
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);
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.
Try this.
for (condition) {
if (!map.containskey(key)) {
map.put(key,value);
}
}
result.add(map);
You have to declare each object outside the for
otherwise you are adding just one reference, and any modification modifies all.