How to initalize a 2D array?

I’m trying to initalize a 2D array at creation. I know that for a single array you go:


int[] i = new int[]{0,1,2,3,4,5,6};

but how do you do it for a 2D array? This is what I got so far:


    int[] i = new int[][]{{0,1,0,1,0,1,0,1,0,1},
    					  {1,0,1,0,1,0,1,0,1,0},
    					  {0,1,0,1,0,1,0,1,0,1},
    					  {0,0,0,0,0,0,0,0,0,0},
    					  {0,0,0,0,0,0,0,0,0,0},
    					  {0,0,0,0,0,0,0,0,0,0},
    					  {0,0,0,0,0,0,0,0,0,0},
    					  {0,0,0,0,0,0,0,0,0,0},
    					  {0,0,0,0,0,0,0,0,0,0},
    					  {0,0,0,0,0,0,0,0,0,0}};

int i[][] = {{0,1,0,1,0,1,0,1,0,1},

etc…

It all looks correct to me, except with the bit:

int[] i = new int[][]

I believe it should be:

int[][] i = new int[][]

Here is info about Java arrays.

Yeah. That one trips up C/C++ guys all the time. Keep in mind that arrays are objects, so the first dimension is an array of references. Means an index can contain nulls or reference any int array, including ones of different lengths, or the same array.

lol, Stranger’s link has it right in a couple of places, but shows the same mistake in the initializing arrays section. ::slight_smile:


int[] oneDim = new int[]{1,2,3};
int[][] twoDim = new int[][]{{1,2,3},{4,5,6},{7,8,9}};
int[][] weirdButLegal = new int[][]{null, oneDim, oneDim , twoDim[1],{7,8,9,10,11,12,13,14,15}};


Alright, thanks everyone! :slight_smile:

Only last year I got the idea of using the intermediate references in 2D arrays.

great solution for row swaping ;D


void swap(int[][] a, int x, int y){
  int[] t = a[x];
  a[x] = a[y];
  a[y] = t;
}

before understading this, I iterated the array, copying the values. :persecutioncomplex: