Got some problem...

This code populates an 2d array and then adds it to an arraylist (all)
It runs 3 times and each time the array place gets different values.
But if you look in arraylist all, the arrays got same value because they point to each other.

If I wanted this to work (and I do) I would need 3 different arrays and add each one of them to the arraylist, then they will have different values because they are different objects.

My problem is that I don't know how many arrays I need from start, it could be 3 it could be 10, 100......

Is there an easy solution for creating new arrays while runtime?
Or can you think of any other solution?

int place = new int [3][3];
ArrayList<int [][]> all = new ArrayList<int[][]>();

int k = 0;
while(k < 3){
    for(int i = 0; i < place.size(); i++){
        for(int j = 0; j < place.size(); j++{
            place[i][j] = k;
        }
    }
    all.add(place);
    k++;
}

Sure, just initialize your array each time the while loop runs, this will create a new data object in memory:

ArrayList<int [][]> all = new ArrayList<int[][]>();
int k = 0;
while(k++ < 3){
	all.add(new int[3][3]);
	int[][] place = all.get(all.size() - 1);
	for(int i = 0; i < place.length; i++) {
		for(int j = 0; j < place.length; j++) {
			place[i][j] = k;
		}
	}
}

an easy solution for creating new arrays while runtime

use the new statement to create a new array. After creating them and filling them, they can be added to the ArrayList.

Ah, how stupid am I XD
place = new int[3][3] did the work, guess I was just tired.

Thanks!

This question has already been answered. Start a new discussion instead.