aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics & Comparator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics & Comparator" Watch "Generics & Comparator" New topic
Author

Generics & Comparator

Nidhi Sar
Ranch Hand

Joined: Oct 19, 2009
Posts: 252

TreeSet class has a constructor which accepts a comparator:

TreeSet(Comparator<? super E> comparator)
Constructs a new, empty tree set, sorted according to the specified comparator.


My question is about the keyword super in comparator. How would a comparator defined for a Parent work for sorting a set of Child objects?

e.g. If the Set is defined as a TreeSet<String>, how can a Comparator<Object> be used to sort it?


"A problem well stated is a problem half solved.” - Charles F. Kettering
SCJP 6, OCPJWCD
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

Nidhi Sar wrote:
e.g. If the Set is defined as a TreeSet<String>, how can a Comparator<Object> be used to sort it?



Agreed. In your example, it is not that useful, as there isn't really any way to sort the Object class.

But what about a different setup... Say you have Object --> Vehicle --> Car --> SUV --> Escalade. And you have a treeset of Escalade, that you just want sorted as a Car, as that is good enough for you. All Escalade are Cars, so why can't you sort it like a car, if you wanted to?

Henry

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
Doesn't the expression <? super E> include E also? So if your
going for TreeSet<String>, Comparator<String> would work
fine. I should think this would be the most common case?
Jim...


BEE MBA PMP SCJP-6
 
jQuery in Action, 2nd edition
 
subject: Generics & Comparator