Alexandru Dragoi wrote:In OCP Oracle Certified Professional Java SE 8 Programmer II, on chapter 3, page 144 we have an implementation of compareTo method:
This implementation may give the wrong answer when there is overflow (comparing a large negative value to a large positive value).
This is a limitation of compare and compareTo methods in that they return int instead of long. There is no way to code these methods to accommodate a range of ids that is wider than half the range of int.
But negative ids wouldn't make sense either
You can do that but ideally the value returned by the method should tell you about the distance between the two objects. If you just return -1 , 0, and 1, you won't be able to order the objects efficiently.
But you are right, "no way" is not the right phrase for what I had in mind.
You are right, Jeanne. As I wrote earlier, I had something else in mind. I was over optimizing. The magnitude of the difference can make ordering a lot more efficient but it is not a goal of compare method.
OP's claim about the code in your book is correct. It will not work for extreme cases.