There's a question in the S&B test exam where ArrayList object (referenced as List) is sorted using a Collections.sort method and printed.
The sort method is invoked with a List object, not a List of Integer's or String's, but a plain old List of Object's. I thought that Object didn't implement Comparable interface and therefore the code above wouldn't compile, or at least throw an exception during the 'sorting'. But no, it compiles, runs and produces output [5, 17, 42, 812].
I guess my question is, how is it possible?
Thanks in advance [ January 11, 2007: Message edited by: Kay Osade ]
If you check the API for Collections.sort, you will see that "All elements in the list must implement the Comparable interface." Integer objects do implement the Comparable interface, so they can be cast to type Comparable for sorting.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Joined: Dec 29, 2006
Yes, the problems begin when a non-Comparable object is cast into one... so instead of taking a List of Comparable objects (whatever they may be - Strings, Integers, etc.), sort method casts the objects that it receives during the RT? That would explain why the compiler didn't complain about getting a List of possibly non-Comparable objects.
Thanks a lot Marc!
P.S. if anyone was wondering, all the objects in the List need to be of the same Comparable type, meaning that you can't stick a String in there, even though Strings are comparable with themselves (but not with Integers). [ January 11, 2007: Message edited by: Kay Osade ]
You can add any type of object to a (non-generic) collection, but if you try to call Collections.sort on it, then the objects need to be Comparable to avoid an exception at runtime.
This is why it's good to make all of your objects Comparable whenever possible (as well as covering some other basics like overridding toString, hashCode, equals, etc.). [ January 11, 2007: Message edited by: marc weber ]