This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics & Comparator" Watch "Generics & Comparator" New topic

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
Henry Wong

Joined: Sep 28, 2004
Posts: 18494

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?


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?

Consider Paul's rocket mass heater.
subject: Generics & Comparator
Similar Threads
How to sort HashSet containing custom Objects...?
Set interface in K&B SCJP book
Creating a Set
TreeSet with compartor constructor