簡體   English   中英

.equals()沒有評估正確的布爾值

[英].equals() not evaluating to proper boolean

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和等於比較器。 如果兩個矩陣的所有鍵和值相等,則返回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

聽起來像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之類的實用方法可能會派上用場。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM