Why does my hashCode
method (btw. generated with Intellij IDEA IDE) return different values for the same object while running the unit test normally and debugging it. While debugging my assert passes and both compared objects are same but when I run the test it results in the false
assertion. Here is the class with hashCode
method:
public class IntegerMatrix {
private static final int HASH_CODE_MULTIPLIER = 31;
/**
* Number of rows.
*/
private int rows;
/**
* Number of columns.
*/
private int columns;
/**
* The actual data.
*/
private int[][] data;
public IntegerMatrix() {
this(0, 0);
}
/**
* Initialization constructor.
*
* @param rows Number of rows.
* @param columns Number of columns.
*/
public IntegerMatrix(int rows, int columns) {
if (rows < 0) {
throw new IllegalArgumentException("Number of rows must be non-negative");
}
if (columns < 0) {
throw new IllegalArgumentException("Number of columns must be non-negative");
}
this.rows = rows;
this.columns = columns;
data = new int[rows][columns];
}
public IntegerMatrix(IntegerMatrix matrix) {
this.rows = matrix.getRows();
this.columns = matrix.getColumns();
this.data = new int[matrix.getRows()][matrix.getColumns()];
}
... some other methods
@Override
public int hashCode() {
int result = rows;
result = HASH_CODE_MULTIPLIER * result + columns;
result = HASH_CODE_MULTIPLIER * result + Arrays.deepHashCode(data);
return result;
}
}
When I create two IntegerMatrix objects and then compare them with auto-generated equals
method (see code below)
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
IntegerMatrix matrix = (IntegerMatrix) o;
return rows == matrix.rows && columns == matrix.columns && Arrays.deepEquals(data, matrix.data);
}
I get true
in debug mode and false
while just running the unit test. Also in debug mode IntegerMatrix#hashCode
returns the same hash code for both matrices (which are actually equal to each other, I personnally controlled the row and columns count as well as data entries) and while running it normally and printing the hash codes to the console gives different ones. Why is it so? What am I missing?
UPDATE
I forgot to notice that mvn test
also runs successfully.