package matrix; /** * * @author Den */ public class Main { public static void main(String[] args) { Matrix m1 = new Matrix(3, 3); try { m1.put(0, 0, 100); m1.put(0, 1, -5); m1.put(0, 2, 0); m1.put(1, 0, 100005); m1.put(1, 1, -20); m1.put(1, 2, 64); m1.put(2, 0, 199910); m1.put(2, 1, -35); m1.put(100, 1000, 128); } catch (MatrixIndex) { } System.out.println(m1.toString()); Matrix m2 = new Matrix(m1); System.out.println(m2.toString()); System.out.println(m1.equals(m2)); Matrix m3 = new Matrix(2, 2); m3.put(0, 0, 10); m3.put(0, 1, 53); m3.put(1, 0, 20); m3.put(1, 1, 106); System.out.println(m3.toString()); System.out.println(m1.equals(m3)); } } } second code file if you want to understand:
package matrix; /** * * @author Den */ public class Matrix { private int row; private int col; private int[][] data; Matrix(int row, int col) { this.row = row; this.col = col; data = new int[row][col]; } Matrix(Matrix matrix) { this.row = matrix.getRow(); this.col = matrix.getCol(); data = new int[row][col]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { data[i][j] = matrix.data[i][j]; } } } public int get(int row, int col) { return data[row][col]; } void put(int row, int col, int value) { data[row][col] = value; } private int getRow() { return row; } private int getCol() { return col; } @Override public boolean equals(Object obj) { Matrix m = (Matrix) obj; if (m.getRow() != row || m.getCol() != col) { return false; } for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (data[i][j] != m.data[i][j]) { return false; } } } return true; } @Override public String toString() { StringBuilder out = new StringBuilder(); out.append("Matrix:\n[ "); for (int i = 0; i < row; i++) { if (i != 0) { out.append("\n"); out.append(" "); } for (int j = 0; j < col; j++) { out.append(data[i][j]); if (j == col - 1) continue; for (int k = 0; k < getMaxLength() - getIntLength(data[i][j]) + 2; k++) { out.append(" "); } } } out.append(" ]"); return out.toString(); } private int getMaxLength() { int max = Integer.MIN_VALUE; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { int k = data[i][j]; if (k > max) { max = k; } } } return getIntLength(max); } private int getIntLength(int i) { return String.valueOf(i).length(); }