• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics & Comparator

 
Nidhi Sar
Ranch Hand
Posts: 252
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Henry Wong
author
Marshal
Pie
Posts: 21008
77
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jim Hoglund
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic