Reputation: 13
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]
Upvotes: 1
Views: 67
Reputation: 1
the reason is in your code, the b.get(0) and b.get(1) point to the same List a, so the output is same.
use this code can achieve what you want, List a1= new ArrayList(); List a2= new ArrayList(); List> b= new ArrayList>();
a1.add("One");
b.add(a1);
a2.add("Two");
b.add(a2);
System.out.println("b="+b.get(0));
System.out.println("b="+b.get(1));
output is, b=[One] 100 b=[Two]
Upvotes: 0
Reputation: 1680
You are adding the same reference in b[0] and b[1]. If you want to have differente lists at diferent index on list b you have to create a new List object
List<String> a= new ArrayList<String>();
List<String> c= new ArrayList<String>();
List<List<String>> b= new ArrayList<List<String>>();
a.add("One");
b.add(a);
c= new ArrayList<String>();
c.addAll(a);
c.add("Two");
b.add(c);
System.out.println("b="+b.get(0));
System.out.println("b="+b.get(1));
Upvotes: 0
Reputation: 394106
You are adding the same List twice, so you see the same elements for both indices of the outer List.
In order to add two different List
s, you must create a new ArrayList
before adding each element to the outer List
:
a.add("One");
b.add(a);
a = new ArrayList<>(a); // assuming you want the second list to contain both "One" and "Two"
a.add("Two");
b.add(a);
Upvotes: 5