I have added an item to list a and then added list a to list b and did the same thing again.
My question is if I print b.get(0) and b.get(1), I am getting the same list that is both the items "One" and "Two", why is it so?
At b.get(0) I want to get only one item I added that is a.add("One").
After adding a.add("Two"), if I print b.get(1) I should get both "One" and "Two"?
Is there any solution or any changes to manage this?
List<String> a= new ArrayList<String>();
List<List<String>> b= new ArrayList<List<String>>();
a.add("One");
b.add(a);
a.add("Two");
b.add(a);
System.out.println("b="+b.get(0));
System.out.println("b="+b.get(1));
output:
b=[One, Two]
b=[One, Two]
ArrayList, hence the Listbat the index one and two refers to the same instance of theArrayList