| Author |
Sort method and Generics
|
Naresh Shanmugam
Ranch Hand
Joined: Jul 16, 2010
Posts: 82
|
|
Sort method in the Collections class looks like this:
public static <T extends Comparable<? super T>> void sort(List<T> list)
I understood the significance of <T extends Comparable> which means the list which implements the comparable interface could be passed as an argument to the sort method.
Consider the below example
class Animal{}
class Dog extends Animal implements Comparable{}
Now i could pass the instance of Dog as the parameter to sort method...
Can any body tell the significance of having <? super T> here Please??
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Take as example java.sql.Timestamp. This class extends java.util.Date which implements Comparable<Date>. Therefore, Timestamp also implements Comparable<Date>.
The <? super T> simply takes these classes into account. If you would have limited it to <T extends Comparable<T>> then you could never use Timestamp, or for example any class that would extend Dog.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Naresh Shanmugam
Ranch Hand
Joined: Jul 16, 2010
Posts: 82
|
|
So a class which directly implements Comparable interface or a class whose super class implements Comparable interface could be passed as a parameter to sort() method.
Rob, please correct me if i am wrong...
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
A class X that implements Comparable<X> -- in other words, any instance can be compared to any other instance. Or a sub class of such a class.
It's the <X> that's very important. I can write a class that can compare itself to Strings:
Because instances of Test cannot be compared to other instances of Test, only to String, it cannot be used in sort().
|
 |
Naresh Shanmugam
Ranch Hand
Joined: Jul 16, 2010
Posts: 82
|
|
Thank you so much for your valuable guidance Rob.. I got the point
I want to become stronger in Generics Could you please suggest me any URL where everything about Generics is explained clearly (or) could you suggest me any text book please...
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
Go to Sun's (or Oracle's these days) tutorial: http://download-llnw.oracle.com/javase/tutorial/
|
 |
 |
|
|
subject: Sort method and Generics
|
|
|