Though Book will use hashCode() implemented in Object class, it's not guaranteed that the hashcode will be always different for different instances. Remember a contract — for 'non-equal' objects it's OK to have same hashcode, and this is named a 'hash collision'. Of course, there is very little probability of facing this behaviour in a single run, but it's indeed greater than zero. To expose it, you may wrap main() contents to an infinite loop and check what second bs.getNumberOfCopies(b) returns in each iteration. If you get patient and wait several minutes you'll see returning 10 somewhat on 10,000,000 or 100,000,000 iteration. Thus, the program will not always throw an exception and sometimes will print 10 10.
It's interesting that the official OCA/OCP JavaSE7 preparation book (Sierra K., Bates B. — OCA OCP Java SE 7 Programmer I & II Study Guide - 2015) contains a question on the same behaviour (Question 4 from Chapter 11 Selftest, page 668), and the answer implies the same — disregarding Object.hashCode() collision. Unfortunately book author ignored my mistake report, so it's unknown if an exam expects from candidates taking into consideration this effect. However, I suppose it would be nice to add at least a remark about this into a question explanation. Like, “but when you successfully passed an exam, welcome to the real life with Object.hashCode() collisions”
For the purpose of the exam, you can assume that it is unique.
The question is already linked to this discussion and so anyone who clicks on it will see this useful information.
HTH,
Paul.
If you like our products and services, please help us by posting your review here.