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()));
}
}- A. false false
- B. true false
- C. false true
- 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
- What is printed? java class Vehicle { void honk() { System.out.print("Beep "); } } class Car extends Vehicle { @Override void honk() {…
- What is printed? java List<String> strings = new ArrayList<>(); List<Integer> ints = new ArrayList<>()…
- What is printed? java class Holder<T extends Number> { T value; Holder(T v) { value = v; } double asDouble() { return value.doubleValue()…
- What is printed? java class Util { static <T> void swap(T[] arr, int i, int j) { T tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } } public…
- What is printed? java public class Main { static <T extends Comparable<T>> T max(T a, T b) { return a.compareTo(b) >= 0 ? a : b; } public…
- Which statement is correct about this class? java public class Base { public void show() { } } class Sub extends Base { private void…