Write a small tester that checks reflexivity, symmetry, null handling and the hashCode rule for pairs of objects; run it on a correct Money class and on a broken class that equals Strings too.
Solution
Main.java
import java.util.Objects;
final class Money {
final String cur;
final long paise;
Money(String cur, long paise) { this.cur = cur; this.paise = paise; }
@Override public boolean equals(Object o) { return o instanceof Money m && paise == m.paise && cur.equals(m.cur); }
@Override public int hashCode() { return Objects.hash(cur, paise); }
}
final class Loose {
final String v;
Loose(String v) { this.v = v; }
@Override public boolean equals(Object o) { return o instanceof Loose l ? v.equals(l.v) : v.equals(o); } // broken
@Override public int hashCode() { return 1; }
}
public class Main {
static String check(Object a, Object b) {
StringBuilder sb = new StringBuilder();
sb.append(a.equals(a) ? "" : " not-reflexive");
sb.append(a.equals(b) == b.equals(a) ? "" : " not-symmetric");
sb.append(!a.equals(null) ? "" : " equals-null");
sb.append(!a.equals(b) || a.hashCode() == b.hashCode() ? "" : " hash-mismatch");
return sb.length() == 0 ? "OK" : sb.toString().trim();
}
public static void main(String[] args) {
System.out.println("Money vs Money: " + check(new Money("INR", 500), new Money("INR", 500)));
System.out.println("Money vs other: " + check(new Money("INR", 500), new Money("USD", 500)));
System.out.println("Loose vs String: " + check(new Loose("x"), "x"));
}
}
Output Verified by compiling and running
Money vs Money: OK
Money vs other: OK
Loose vs String: not-symmetric hash-mismatch
Loose says it equals "x", but "x".equals(loose) is false – the symmetry rule is broken. And since loose.equals("x") is true while their hash codes differ (1 vs 120), the hashCode rule is broken too.
More Object Class and Wrapper Classes practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!