问题描述
public class Matrix { int rows; int cols; double data[][]; public Matrix() { this(0, 0); } public Matrix(int rows, int cols) { this(rows, cols, new double[rows][cols]); //后面为什么要创建new double[rows][cols] } public Matrix(int rows, int cols, double[][] data) { super(); //为什么要调用父类的构造方法 this.rows = rows; this.cols = cols; this.data = data; } public double getData(int row, int col) { return data[row][col]; } public void setData(int row, int col, double value) { data[row][col] = value; } public double[][] multiply(double[][] m2) { int m1rows = data.length; int m1cols = data[0].length; int m2rows = m2.length; int m2cols = m2[0].length; if (m1cols != m2rows) throw new IllegalArgumentException("matrix doesn't match"); double[][] result = new double[m1rows][m2cols]; // multiply for (int i = 0; i < m1rows; i++) for (int j = 0; j < m2cols; j++) for (int k = 0; k < m1cols; k++) result[i][j] += data[i][k] * m2[k][j]; return result; } public String toString() { StringBuffer sb = new StringBuffer(); int rows = data.length; int cols = data[0].length; sb.append("array[" + rows + "][" + cols + "] = " + "n"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) sb.append(" " + data[i][j] + " "); sb.append("n"); } sb.append("n"); return sb.toString(); } public static void main(String[] argv) { double x[][] = { { 3, 2, 3 }, { 5, 9, 8 }, }; Matrix m = new Matrix(3, 2, x); double y[][] = { { 4, 7 }, { 9, 3 }, { 8, 1 }, }; double z[][] = m.multiply(y); Matrix zm = new Matrix(z.length, z[0].length, z); // print result System.out.println(zm); } }
解决方案
this(rows, cols, new double[rows][cols]); //后面为什么要创建new double[rows][cols] 这句话的意思就是调用该类的其他构造方法,你底下还有个构造方法,如果你有看JDK底层代码,里面有很多都有N种构造方法,一环镶嵌一环,这是设计的时候设计的public Matrix(int rows, int cols, double[][] data) {//也就是调用这句 super(); //为什么要调用父类的构造方法 this.rows = rows; this.cols = cols; this.data = data; } 至于为什么要调用父类,你这没有使用继承,应该没什么用 public String toString() { StringBuffer sb = new StringBuffer(); int rows = data.length; int cols = data[0].length; sb.append("array[" + rows + "][" + cols + "] = " + "n"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) sb.append(" " + data[i][j] + " "); sb.append("n"); } sb.append("n"); return sb.toString(); } toString 是从写方法,也就是如果你需要打印出该类,只要直接调用new Matrix();就OK了
解决方案二:
this(rows, cols, new double[rows][cols]); //后面为什么要创建new double[rows][cols] 这个之所以要创建new double[rows][cols]是为了传递给this()方法,this()方法指的就是下面那个public Matrix(int rows, int cols, double[][] data)为什么要调用父类的构造方法 这个调用父类构造方法多余,直接去掉就可以toString()方法中的那些代码都是为了生成可以阅读的Matrix信息,这样如果你System.out.println(new Matrix())的时候JAVA或自动调用这个toString()方法把这些比较容易看懂的矩阵信息输入到控制台
解决方案三:
this(rows, cols, new double[rows][cols]); //后面为什么要创建new double[rows][cols] ??这个是给data数组了一个初始大小,默认大小是0。super(); //为什么要调用父类的构造方法??这个调用无任何意义,可以不调。后面toString是想让输出格式显示的好看一点。