An easy enough solution of the top of the head would be to take the contents of the first array and store them in a temporary 1 dimensional array. Then transfer them over to your new array. Probably an easier way but its the first thing I thought of. I just threw the code into a pair of methods.
class Copy2dArray
{
//Copies the contents of a 2d array into another 2d array
//@PARAM The array to be copied and the two values determining the size of
//the M * N sized array to be created. mDim = M, nDim = N.
static int[][] copy2dArrayContents(int[][] original, int mDim, int nDim)
{
int[] arrayTemp = new int[mDim*nDim]; //nDim * mDim is the max amount of elements that the copy can store, as specified by user
int[][] copy = new int[mDim][nDim]; //array with specified dimension to store the copied contents
int tempIndex = 0;
//Copy array1 contents into arrayTemp
for(int i = 0; i < original.length; i++)
{
for(int j = 0; j < original[i].length; j++)
{
arrayTemp[tempIndex] = original[i][j];
tempIndex++;
}
}
tempIndex = 0;
for(int i = 0; i < copy.length; i++)
{
for(int j = 0; j < copy[i].length; j++)
{
copy[i][j] = arrayTemp[tempIndex];
tempIndex++;
}
}
return copy;
}
//print out a 2d array to STD output
//@PARAM The array to be printed
static void print2dArray(int[][] array)
{
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
System.out.print(array[i][j] + " ");
}
}
System.out.println("");
}
public static void main(String[] args)
{
//Declare variables
int[][] array1 = new int[4][6]; //Original array
int[][] array2 = new int[3][8]; //Array to be copied to
int start = 1;
//Initialize array1 with numbers 1 - 24
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 6; j++)
{
array1[i][j] = start;
start++;
}
}
//Copy array1 contents into array2
array2 = copy2dArrayContents(array1, 3, 8);
//print both arrays to standard output
print2dArray(array1);
print2dArray(array2);
}
}
Resulting Output:
L:\Code\Java\java Copy2dArray
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24