Programming and Problem Solving with Java

(やまだぃちぅ) #1

CASE STUDY


608


Responsibility Algorithms:To create the matrix, we need a constructor that takes the
number of rows and the number of columns as parameters and creates the array.

publicMatrix(introws, intcolumns)
// Create empty matrix
{
matrix = new double[rows][columns];
}

Now that we know the internal structure is an array, we can give the client an alter-
native constructor that takes the array of values as data rather than having to input
one value at a time. This constructor makes a shallow copy of the array. Case Study
Follow-up Exercise 5 asks you to rewrite this constructor to make a deep copy.

publicMatrix(double[][] data)
// Stores the reference argument into matrix
{
matrix = data;
}

The next method simply asks the object to return a copy of an item at a particular
slot in the array.

public doubleknowValueAt(introw, intcol)
// Returns the value at matrix[row][col]
{
returnmatrix[row][col];
}

The next two observer methods return the number of rows and the number of
columns. Because Java implements a two-dimensional array as an array of references
to arrays and each one-dimensional array object has an instance variable that contains
the number of slots in the array, we have direct access to this information. The length
field of the two-dimensional array gives the number of rows; the lengthof each row
gives the number of columns in that row. We do not need to worry about ragged arrays
because of the way that we have implemented the constructor.

public intknowRows()
// Returns the number of rows in matrix
{
returnmatrix.length;
}

public intknowColumns()
// Returns the number of columns in matrix
Free download pdf