This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I bought the SCJP 5 Study Guide by KAthy Sierra and Bert Bates quite a while ago, and today I decided to go through the exams on the CD that came with it.
I noticed there is one huge error in the exam on there. It's question 12 I believe:
Which of the following will fulfill the equals() and hashCode() contracts for this class? (Choose all that apply.) A) return ((SortOf)o).bal == this.bal; B) return ((SortOf)o).code.length() == this.code.length(); 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;
According to the software, C and D must be the answers.
I see why A and B are wrong, but I strongly believe D is wrong as well, and I can even show it with an example.
Consider two SortOf objects: - a with code == "a", bal = 5 and rate = 2 - b with code == "b", bal = 2 and rate = 5
According to the equals implementation of D, these objects are equal: 1 * 5 * 2 == 1 * 2 * 5. However, these objects have different hash codes: the hash code of a is 1 * 5 == 5, whereas the hash code of b is 1 * 2 == 2. Therefore, answer D clearly violates the contract (equal objects must have equal hash codes), and cannot be correct.