MasterExam Quiz A
Which of the following will fulfill the equals() and hashCode() contracts for this class?
According to the MasterExam, the following two are correct answers:
C. return ((SortOf)o).code.length() * ((SortOf)o).bal == this.code.length() * this.bal;
D. return ((SortOf)o).code.length() * ((SortOf)o).bal * ((SortOf)o).rate == this.code.length() * this.bal * this.rate;
C is ok. But I've query about the D. In this case, there is a scope of breaking hashCode() and equals() contracts. The second contract of the hashCode() states that, "if two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result."
Now, suppose there are two SortOf objects - the first object is s1, where code = "ja", bal = 2, and rate = 5 and the second object is s2, where code = "va", bal = 5, and rate = 2.
According to the above two objects and the D answer, the equals(Object) method will return true but for the first object the hashCode() will return 4 and for the second object hashCode() will return 10.
How should we tackle this type of question?