ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Matrix {
    int[][] data;
    Matrix(int n) { data = new int[n][n]; }
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Matrix m)) return false;
        return java.util.Arrays.deepEquals(data, m.data);
    }
    @Override
    public int hashCode() { return java.util.Arrays.deepHashCode(data); }
}
public class Main {
    public static void main(String[] args) {
        Matrix m1 = new Matrix(2);
        Matrix m2 = new Matrix(2);
        System.out.println(m1.equals(m2) + " " + (m1.hashCode() == m2.hashCode()));
    }
}
  1. A. false false
  2. B. true false
  3. C. false true
  4. D. true true

Correct answer: D. true true

Both matrices are freshly allocated 2x2 int arrays, all entries defaulting to 0, so deepEquals finds them structurally identical, making equals() true. deepHashCode() computes a hash purely from the (identical) contents, so both hash codes match too, making the comparison true as well.

More OOP with C++ and Java questions

Exams that ask this topic