Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sort method and Generics

 
Naresh Shanmugam
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20751
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Naresh Shanmugam
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20751
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20751
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Go to Sun's (or Oracle's these days) tutorial: http://download-llnw.oracle.com/javase/tutorial/
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic