| Author |
collections
|
radhika ayirala
Greenhorn
Joined: Aug 28, 2007
Posts: 24
|
|
import java.util.*; class test implements Comparator<test> { private int x; test(int input) { x = input; } public static void main( String args[] ) { List list = new ArrayList(); list.add(new test(2)); list.add(new test(2)); Collections.sort(list); } public int compare( test t1 , test t2 ) { return t1.x - t2.x; } } The explanation for the above program. This code will throw a ClassCastException. This version of Collections.sort() banks on the Comparable interface being implemented, not the Comparator interface. No comparator is passed to the sort() method. I couldn't understand the above explanation.Please explain.
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
The Collections class has 2 sort methods: sort(List list)sort(List list, Comparator c) If you use the version with the Comparator, then that Comparator is used to sort the List. However, if you use the one that takes only a List, then it treats the List's elements as being Comparable (that is, implementing the Comparable interface). In this example, no Comparator is supplied to the sort method, and the elements are not Comparable. [ September 18, 2007: Message edited by: marc weber ]
|
"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
|
 |
radhika ayirala
Greenhorn
Joined: Aug 28, 2007
Posts: 24
|
|
|
I got it.Thanks.Can you please tell me,why elements are not comparable.
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
Originally posted by radhika ayirala: I got it.Thanks.Can you please tell me,why elements are not comparable.
When we say an object is "Comparable," we mean it implements the Comparable interface, overriding its compareTo method. So it literally IS-A Comparable. The sort method must try to upcast to type Comparable, which is why it throws a ClassCastException if the elements are not Comparable. In this example, the class implements Comparator, but not Comparable.
|
 |
radhika ayirala
Greenhorn
Joined: Aug 28, 2007
Posts: 24
|
|
|
thanks
|
 |
 |
|
|
subject: collections
|
|
|