实现矩阵的加减法运算以及equals()方法和toString()方法
时间: 2023-05-28 12:05:41 浏览: 86
以下是Java代码示例:
```java
public class Matrix {
private int rows;
private int cols;
private int[][] data;
public Matrix(int rows, int cols) {
this.rows = rows;
this.cols = cols;
this.data = new int[rows][cols];
}
public int getRows() {
return rows;
}
public int getCols() {
return cols;
}
public int getValue(int row, int col) {
return data[row][col];
}
public void setValue(int row, int col, int value) {
data[row][col] = value;
}
public Matrix add(Matrix other) {
if (this.rows != other.getRows() || this.cols != other.getCols()) {
throw new IllegalArgumentException("Matrix dimensions must be equal");
}
Matrix result = new Matrix(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result.setValue(i, j, this.getValue(i, j) + other.getValue(i, j));
}
}
return result;
}
public Matrix subtract(Matrix other) {
if (this.rows != other.getRows() || this.cols != other.getCols()) {
throw new IllegalArgumentException("Matrix dimensions must be equal");
}
Matrix result = new Matrix(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result.setValue(i, j, this.getValue(i, j) - other.getValue(i, j));
}
}
return result;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Matrix)) {
return false;
}
Matrix other = (Matrix) obj;
if (this.rows != other.getRows() || this.cols != other.getCols()) {
return false;
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (this.getValue(i, j) != other.getValue(i, j)) {
return false;
}
}
}
return true;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sb.append(this.getValue(i, j)).append(" ");
}
sb.append("\n");
}
return sb.toString();
}
}
```
在这个示例中,我们定义了一个Matrix类,包含以下方法:
- 构造函数:创建一个指定行和列的矩阵,并初始化所有元素为0。
- getRows()和getCols()方法:获取矩阵的行数和列数。
- getValue()和setValue()方法:获取和设置矩阵中指定位置的值。
- add()方法:将当前矩阵和另一个矩阵相加,返回结果矩阵。
- subtract()方法:将当前矩阵和另一个矩阵相减,返回结果矩阵。
- equals()方法:检查两个矩阵是否相等。
- toString()方法:将矩阵转换为字符串,以便输出到控制台。
我们可以使用以下代码来测试Matrix类的功能:
```java
Matrix m1 = new Matrix(2, 2);
m1.setValue(0, 0, 1);
m1.setValue(0, 1, 2);
m1.setValue(1, 0, 3);
m1.setValue(1, 1, 4);
System.out.println("m1:\n" + m1);
Matrix m2 = new Matrix(2, 2);
m2.setValue(0, 0, 5);
m2.setValue(0, 1, 6);
m2.setValue(1, 0, 7);
m2.setValue(1, 1, 8);
System.out.println("m2:\n" + m2);
Matrix m3 = m1.add(m2);
System.out.println("m1 + m2:\n" + m3);
Matrix m4 = m1.subtract(m2);
System.out.println("m1 - m2:\n" + m4);
System.out.println("m1 equals m2? " + m1.equals(m2));
System.out.println("m1 equals m1? " + m1.equals(m1));
```
输出结果如下:
```
m1:
1 2
3 4
m2:
5 6
7 8
m1 + m2:
6 8
10 12
m1 - m2:
-4 -4
-4 -4
m1 equals m2? false
m1 equals m1? true
```