I am trying to use ArrayList<ArrayList<String>>
to parse some fragment from web page but something goes wrong within my code:
ArrayList<ArrayList<String>> x = new ArrayList<ArrayList<String>>();
ArrayList<String> s = new ArrayList<String>();
int z, y, w = 0;
for(z=0; z<3;z++)
{
s.clear();
for(y=0;y<4;y++)
{
s.add(""+w++);
}
x.add(s);
}
for(ArrayList<String> tr : x)
{
for( String t : tr)
{
System.out.println(t);
}
System.out.println("-----------------");
}
The output is:
8
9
10
11
8
9
10
11
8
9
10
11
instead of ( my expected output ):
0
1
2
3
4
5
6
7
8
9
10
11
Can somebody explain to me why is this happening? Thanks.
It is expected behavior of Object inside loops , Because s
is a same object in every iteration, you need to create new object in your loop.
change your code like this:
for(z=0; z<3;z++)
{
s = new ArrayList<String>();
for(y=0;y<4;y++)
{
s.add(""+w++);
}
x.add(s);
}
You are adding the same inner ArrayList reference to the outer ArrayList multiple times. Therefore all the inner ArrayList
s are the same object, and contain the same elements.
You must create a new instance for each iteration of the outer loop :
for(z=0; z<3;z++)
{
s = new ArrayList<String>();
for(y=0;y<4;y++)
{
s.add(""+w++);
}
x.add(s);
}
The above program reuses the same ArrayList (inner list: s) over and over and hence you get only the last set of values,
Move the line 2 (inner Arraylist initialization) to inside the loop as follows to get the desired result,
ArrayList<ArrayList<String>> x = new ArrayList<ArrayList<String>>();
int z,y,w=0;
for(z=0; z<3;z++)
{
ArrayList<String> s = new ArrayList<String>();
for(y=0;y<4;y++)
{
s.add(""+w++);
}
x.add(s);
}
for(ArrayList<String> tr : x)
{
for( String t : tr)
{
System.out.println(t);
}
System.out.println("-----------------");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.