4
public class SparseMatrix {
    private final TreeMap<Integer,TreeMap<Integer,Double>> matrix;
    private final int rows;
    private final int cols;

    public SparseMatrix(int r, int c) {
        // Creates instances for matrix objects
        this.matrix = new TreeMap<>();

        // Assigns the matrix a number of rows and a number of columns
        this.rows = r;
        this.cols =  c;
    }

    public TreeMap<Integer, TreeMap<Integer, Double>> getMatrix() {
        return matrix;
    }

    public static boolean equals(SparseMatrix a, SparseMatrix b) {
        if (a.getMatrix().equals(b.getMatrix()) == true) {
            return true;
        }
        else {
            return false;
        }
    }
}

键和值由用户输入,然后有一个测试驱动程序来确保它正常工作,但它没有正确评估矩阵。它每次都告诉我真的。我假设它是 == true 和 equals 比较器。如果两个矩阵的所有键和值都相等,则返回 true。

“新”命令:

if (cmd.equals("new")) {
    String name = input.next();
    int rows = input.nextInt();
    int cols = input.nextInt();
    if (rows < 1 || cols < 1) {
        System.out.println("new: rows and/or cols less than 1: ");
        System.exit(1);
    }

    SparseMatrix m = new SparseMatrix(rows,cols);
    int i = input.nextInt();
    while (i >= 0) {
        int j = input.nextInt();
        double v = input.nextDouble();
        m.set(i,j,v);
        i = input.nextInt();
    }
    matrix.put(name,m);
    System.out.printf("new %s = %s\n", name, m);
}

测试驱动部分是:

String a = input.next();
if (!matrix.containsKey(a)) {
    System.out.println("equals: no such matrix: " + a);
    System.exit(1);
}
String b = input.next();

if (!matrix.containsKey(b)) {
    System.out.println("equals: no such matrix: " + b);
    System.exit(1);
}

System.out.printf("%s.equals(%s) = %b\n", a, b,
              SparseMatrix.equals(matrix.get(a),matrix.get(b)));

输入看起来像:

new name1 10 10 // new matrix with 10 rows and 10 columns
10 10 10.0 // int int double treemap
-1 // stops the input
4

1 回答 1

0

听起来matrix.get(a)matrix.get(b)返回相同TreeMap。尝试打印结果以确保。

至于比较,只要您尝试正确比较的对象覆盖equals,您就可以使用标准 API 执行此操作:

public static boolean equals(SparseMatrix a, SparseMatrix b) {
    return matrix.get(a).equals(matrix.get(b));
}

我也是Apache CommonsGuava等库的忠实粉丝。Commons Collections.isEqualCollection和 Guava Maps.difference等实用方法可能会派上用场。

于 2013-11-22T17:32:52.497 回答