ProgrammingHardTCS NQT · Infosys pattern
Which statement about overriding equals() correctly describes the contract that must hold?
- A. If equals() is overridden, hashCode() may be left as the default identity hash with no consequence
- B. equals() must always compare object references, never field values
- C. equals() only needs to be reflexive; symmetry and transitivity are optional for custom classes
- D. equals() must be reflexive, symmetric, transitive, and consistent, and x.equals(null) must always return false
Correct answer: D. equals() must be reflexive, symmetric, transitive, and consistent, and x.equals(null) must always return false
The Object.equals() contract requires reflexivity (x.equals(x)), symmetry (x.equals(y) iff y.equals(x)), transitivity, consistency across repeated calls (if no mutation), and x.equals(null) == false. Breaking any of these, or overriding equals() without hashCode(), causes subtle bugs in hash-based collections.
More OOP with C++ and Java questions
- What is printed? java class Animal { String name; Animal(String n) { name = n; } @Override public boolean equals(Object o) { if (!(o…
- What is printed? java public class Main { public static void main(String[] args) { Integer a = 127; int b = 127; System.out.print(a == b)…
- What is printed? java public class Main { public static void main(String[] args) { String s1 = "java"; String s2 = "java".intern(); String…
- What is printed? java public class Main { public static void main(String[] args) { String s = "hello"; String t = s; t = t.concat("…
- What is printed? java public class Main { public static void main(String[] args) { Object o1 = new Object(); Object o2 = new Object()…
- What is printed? java public class Main { public static void main(String[] args) { List<String> list = new ArrayList<>(Arrays.asList("a"…