Data Structures, Algorithms, & Applications in Java
Chapter 5, Exercise 3
The code is given below.
/** Change the dimensions of a 2D array */
package utilities;
import java.lang.reflect.*;
public class Change2DArrayLength
{
/** @param rows is number of rows of a to be copied into new array
* @param columns is number of columns of a to be copied into new array
* @return a newRows x newColumns array
* @throws IllegalArgumentException when rows > newRows
* or columns > newColumns
* input array a must have at least 1 row */
public static Object [][] changeLength2D(Object [][] a,
int rows, int columns, int newRows, int newColumns)
{
// make sure new dimensions are adequate
if (rows > newRows || columns > newColumns)
throw new IllegalArgumentException
("new dimensions are too small, rows = " + rows
+ " columns = " + columns + " newRows = " + newRows
+ " newColumns = " + newColumns);
// set up array of new dimensions
int [] dimensions = {newRows, newColumns};
// allocate a new array of desired dimensions and type
Object [][] newArray = (Object [][]) Array.newInstance
(a[0].getClass().getComponentType(), dimensions);
// copy from old space to new space
for (int i = 0; i < rows; i++)
// copy row i
System.arraycopy(a[i], 0, newArray[i], 0, columns);
return newArray;
}
}