Question 14
Back to Exercise
What is the output of the following Java program?
class CaseInsensitive {
final String s;
CaseInsensitive(String s) { this.s = s; }
@Override public boolean equals(Object o) {
if (o instanceof CaseInsensitive c) return s.equalsIgnoreCase(c.s);
if (o instanceof String str) return s.equalsIgnoreCase(str); // tries to equal Strings too
return false;
}
@Override public int hashCode() { return s.toLowerCase().hashCode(); }
}
public class Main {
public static void main(String[] args) {
CaseInsensitive ci = new CaseInsensitive("Java");
String str = "java";
System.out.println(ci.equals(str) + " " + str.equals(ci) + " " + ci.equals(new CaseInsensitive("JAVA")));
}
}
- A true false true Correct
- B true true true
- C false false true
- D true false false
Correct Answer: Option A
String.equals knows nothing about CaseInsensitive, so symmetry is broken – a classic example of why equals should only accept its own type.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!