Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collections.sort

 
Kay Osade
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Try this...
 
Kay Osade
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that if you use JDK 5+, the sort() method is defined as

This, ahhh, encourages you to use a List of some sort of Comparables. But the code shown uses a raw ArrayList type, which means that the generics info is ignored, and a compiler warning is generated.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic