This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Sort method and Generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Sort method and Generics" Watch "Sort method and Generics" New topic
Author

Sort method and Generics

Naresh Shanmugam
Ranch Hand

Joined: Jul 16, 2010
Posts: 86
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: 20078
    
  30

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 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
Naresh Shanmugam
Ranch Hand

Joined: Jul 16, 2010
Posts: 86
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: 20078
    
  30

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: 86
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: 20078
    
  30

Go to Sun's (or Oracle's these days) tutorial: http://download-llnw.oracle.com/javase/tutorial/
 
Have you checked out Aspose?
 
subject: Sort method and Generics
 
It's not a secret anymore!