wood burning stoves
The moose likes Beginning Java and the fly likes Collections comparable interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Collections comparable interface" Watch "Collections comparable interface" New topic

Collections comparable interface

Shaveta Chawla

Joined: Aug 01, 2007
Posts: 13

I understood the concept of Comparable interface and how it is used and the advantages of using comparator interface over comparable interface. But i am still confused that when we invoke the sort() method of Collections class
Collections.sort(List l);

How did it know that type of List should implement comparable interface?

Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15093

The list does not implement the Comparable interface - the class of the objects in the list must implement the Comparable interface.

The sort() method needs this, because it must be able to compare objects in the list to determine which comes before which in the sorted result.

The API documentation of the method Collections.sort() tells you this:
Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface.

[ August 09, 2007: Message edited by: Jesper Young ]

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link: http://aspose.com/file-tools
subject: Collections comparable interface
It's not a secret anymore!