I'm trying to add Objects ( in this example to keep it simple Strings) to Arraylists, that are collected as an Arraylist. Here is the code:
public static void main(String[] args) {
ArrayList dummylist = new ArrayList();
ArrayList<ArrayList<String>> dummylistlist = new ArrayList<ArrayList<String>>();
for (int j=0; j< 2; j++){
dummylistlist.add(dummylist);
String text = "test";
dummylistlist.get(j).add(text);
}
for (int j=0; j< 2; j++){
System.out.println("arraylist "+j+" has size "+dummylistlist.get(j).size());
System.out.println("Arraylist No."+j+" is ="+dummylistlist.get(j));
}
}
And the output is:
arraylist 0 has size 2
Arraylist No.0 is =[test, test]
arraylist 1 has size 2
Arraylist No.1 is =[test, test]
But I expected it to be:
arraylist 0 has size 1
Arraylist No.0 is =[test]
arraylist 1 has size 1
Arraylist No.1 is =[test]
Why does the method add(text) appends the "test" String to all sublists so that it gets added once each loop? I don't understand. Can you help me to fix my code to achieve the latter output? Thank you in advance.