package edu.hawaii.ics.yucheng; import java.util.ArrayList; /** * A generic matrix class. * * @param <T> The type stored as matrix elements. */ class Matrix<T> { private final ArrayList<T> myArray; private final int myColumns; private final int myRows; /** * Initializes a new instance of the class. * * @param rows The number of rows. * * @param columns The number of columns. * * @param defaultValue The default value. */ public Matrix(final int rows, final int columns, final T defaultValue) { if (rows <= 0) throw new IllegalArgumentException("rows"); if (columns <= 0) throw new IllegalArgumentException("columns"); // Store the fields, and initialize the array. myColumns = columns; myRows = rows; myArray = new ArrayList<T>(rows * columns); for (int r = 0; r < rows; r++) for (int c = 0; c < columns; c++) myArray.add(defaultValue); } /** * Clones a matrix. * * @param matrix The matrix to clone. */ protected Matrix(final Matrix<T> matrix) { myColumns = matrix.myColumns; myRows = matrix.myRows; myArray = new ArrayList<T>(matrix.myArray); } /** * Returns a clone of the matrix. * * @return A clone of the matrix. */ @Override public Matrix<T> clone() { return new Matrix<T>(this); } /** * Returns the number of columns. * * @return The number of columns. */ public int columns() { return myColumns; } /** * Returns the element value at a specified position. * * @param row The row. * * @param column The column. * * @return The element. */ public T get(final int row, final int column) { if (row < 0 || row >= myRows) throw new IndexOutOfBoundsException("row"); if (column < 0 || column >= myColumns) throw new IndexOutOfBoundsException("column"); return myArray.get(row * myRows + column); } /** * Returns the number of rows. * * @return The number of rows. */ public int rows() { return myRows; } /** * Sets the element value at the specified position. * * @param row The row. * * @param column The column. * * @param value The value. */ public void set(final int row, final int column, final T value) { if (row < 0 || row >= myRows) throw new IndexOutOfBoundsException("row"); if (column < 0 || column >= myColumns) throw new IndexOutOfBoundsException("column"); myArray.set(row * myRows + column, value); } /** * Returns the string representation of the class. * * @return The string representation of the class. */ @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("{"); for (int row = 0; row < myRows; row++) { builder.append(" {"); for (int column = 0; column < myColumns; column++) builder.append(" " + get(row, column).toString()); builder.append(" }"); if (row + 1 < myColumns) builder.append("\n "); } builder.append(" }"); return builder.toString(); } }