TheAlgorithms / Java

All Algorithms implemented in Java
MIT License
60.03k stars 19.39k forks source link

Matrix equality comparison is shallow. #719

Closed Egoscio-zz closed 5 years ago

Egoscio-zz commented 5 years ago

The matrix class and the tests written for it only support shallow comparison. In other words, comparisons only verify whether two matrices have the same reference rather than actually comparing each element in the matrix.

int[][] data = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };
int[][] zeroData = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 } };
Matrix matrix = new Matrix(data);
Matrix zeroMatrix = new Matrix(zeroData);
System.out.println(matrix);
System.out.println(matrix.plus(zeroMatrix));
System.out.println(matrix.equals(matrix.plus(zeroMatrix)));

The above equality should equate to true, since a matrix plus the zero matrix is itself (identity property of matrix addition), but instead, it equates to false. Deep comparison is necessary, in the same way a deep copy of the data is made in the matrix constructor.

a-deeb commented 5 years ago

would this fix it?

public boolean equals(Matrix other) { //return this == other; return this.equals(other); }

Egoscio-zz commented 5 years ago

That's going to give you a StackOverflowError exception because you're recursively defining the equals function.