1

Here is my code. In my case list is getting over ridden. output should be [[1][1,1][1,2,1][1,3,3,1][1,4,6,4,1] I am getting like - [[1, 4, 6, 4, 1], [1, 4, 6, 4, 1], [1, 4, 6, 4, 1], [1, 4, 6, 4, 1], [1, 4, 6, 4, 1]]. which is latest value in the loop repeated. what might be the problem

int i,j;
i=0;
j=0;
int a;
Integer temp;
a = 5;
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> list1 = new ArrayList<Integer>();

for ( i =0 ;i<a ;i++)
{
    list1.clear();

    Integer number; 
    number = (int) Math.pow(11, i);
    LinkedList<Integer> stack = new LinkedList<Integer>();
    while (number > 0) {
        stack.push( number % 10 );
        number = number / 10;
    }

    while (!stack.isEmpty()) {
        temp = (stack.pop());
        list1.add(temp);    
    }
    list.add(list1);
}
System.out.println("The arraylist contains the following elements: "+ list);
Deximus
  • 455
  • 5
  • 8
Vinay K L
  • 91
  • 1
  • 1
  • 8

2 Answers2

0

It seems like you are cleaning your List1 array every time. And you have only one array list inside large array list. So you end up with the last results you put on inner arraylist. To get expected results, you shoud create several arraylists inside the for loop.

udakarajd
  • 114
  • 11
0

Replace list1.clear() with list1 = new ArrayList<Integer>();

In Java it is call by value. But when say list1 you only have the reference to list1.

So when you are iterating, you are doing list1.clear. What it does it clears the list pointed to by the reference list1. This will clear the list that you added into the list. So what you get at the end is the latest content of list1.

For a detailed understanding, refer to this

Community
  • 1
  • 1
Thiyagu
  • 17,362
  • 5
  • 42
  • 79