Matthew Brown wrote:What the compareTo method wants to do is subtract the i value of obj from the i value of the object it's called on. But you can't just write i - obj.i, because obj is an Object reference, and i doesn't exist in the Object class. So we need to perform a "cast".
(B)obj is a cast statement. It converts the Object reference to a B reference, so you can access the members of the B class (i, in this case). Note that it doesn't change the object itself, so it will only work if the object really is a B. If it isn't you'll get a ClassCastException.
So i - obj.i becomes i - ((B)obj).i - with the extra brackets because the . has higher precedence than the cast.
By the way, the cast isn't necessary if you use generics (which you really should):
As to when it gets called - the most common reason would be that you're using a sort function such as Collections.sort(). A sort function can't sort objects unless it knows how to compare two objects. That's what we do when we implement Comparable - we're saying "when you compare two objects of this type, this is how we want you to do it".
Campbell Ritchie wrote:And what does this line mean?As Matthew says, you should really use generics. Putting suppress instructions into your code can cause you to miss serious type errors which can cause Exceptions and cause your program to crash later on.
kiran kumar reddy wrote:why is that the value of obj differing from i??
But you are still wrong to use the suppress instruction.kiran kumar reddy wrote: . . . i am following a book in which it has colletions API first and generics is the next topic of it. so i am not using generics . . .
kiran kumar reddy wrote:mean how it got sorted. program flow
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here