Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^590) | Multidimensional Arrays and Numeric Computation
processing has the row index in the outer loop, and column processing has the column in-
dex in the outer loop.
Row Processing
for (int row = minRow; row < rowsFilled; row++)
for (int col = minCol; col < colsFilled; col++)
// Whatever processing is required
Column Processing
for (int col = minCol; col < colsFilled; col++)
for (int row = minRow; row < rowsFilled; row++)
// Whatever processing is required


Two-Dimensional Arrays and Methods


A two-dimensional array can be a parameter in a method, and it can be the return value type
for a method. The syntax and semantics are identical to those for one-dimensional arrays
except we use an additional pair of brackets. Let’s enclose the array initialization code frag-
ment within a method:

voidinitialize(int[][] data)
// Set every cell in data to -1
{
for (int row = 0; row < data.length; row++)
for (int col = 0; col < data[row].length; col++)
data[row][col] = -1;
}

Because Java has a field associated with each array that contains the number of slots de-
fined for the array, we do not have to pass this information as a parameter as we do in many
other languages. This ability is a consequence of the object orientation of the language. The
array is an object and the information about the object is encapsulated with it.
As an example of a value-returning method, let’s design one that returns a copy of the
array passed as a parameter. All the information we need to instantiate the new array is
present in the array passed as a parameter. We just instantiate it and copy in the values.

int[][] copy(int[][] data)
// Returns a deep copy of data, assuming data is not ragged
{
int[][] copyData = new int[data.length] [data[0].length];
for (int row = 0; row < data.length; row++)
for (int col = 0; col < data[row].length; col++)
copyData[row][col] = data[row][col];
returncopyData;
}

T


E


A


M


F


L


Y


Team-Fly®

Free download pdf