i am working with list insertion in map and not able to understand the insertion behaviour.
public class TestList {
public static void main(String[] args) {
String strarray[] = new String[5];
for(int i = 0; i < 5; i++ ){
strarray[i] = "Demo" + i;
}
Map<Integer, List<String>> cluesByText = new HashMap<Integer, List<String>>();
int j = 0;
for (String str : strarray) {
System.out.println(str);
List<String> s = cluesByText.get(str);
if (s == null) {
s = new LinkedList<String>();
cluesByText.put(j, s);
}
s.add(str);
s.add(str);
s.add(str);
s.remove(1);
// why it is storing without doing cluesByText.put(j,s);
j++;
}
//output is:
System.out.println(cluesByText);
}
}
Problem is while doing insertion of list into the map and then on changing the contents of list by insert/delete operation , it is getting reflected in the list which was stored in map in previous line.
final output coming on printing map contents is.
{0=[Demo0, Demo0], 1=[Demo1, Demo1], 2=[Demo2, Demo2], 3=[Demo3, Demo3], 4=[Demo4, Demo4]}
i am not able to understand why it happening in this way as state of list is already been stored in map?