0

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.

1
  • s is a reference to an object. When you add a copy of this reference it just adds that reference, not a copy of the object referenced. Commented Jun 6, 2015 at 14:10

3 Answers 3

8

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Such stupid mistake.. Thanks guys for help, I've forgotten that add method doesn't make a copy of an object.
@PatLas glad to be helpful :)
2

You are adding the same inner ArrayList reference to the outer ArrayList multiple times. Therefore all the inner ArrayLists 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);
}

Comments

0

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("-----------------");
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.