Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of super in Comparator in java

I understand in

Comparator < ? super T> comp

it returns the maximum element of the given collection, according to the order defined by the specified comparator. But I don't understand the purpose of the

super T

Could anyone possibly explain?

like image 684
Marcello Avatar asked Dec 09 '12 09:12

Marcello


People also ask

What is the use of Comparator in Java?

Comparator is used in Java to sort objects based on multiple data members (i.e) based on any conditions because Comparable can be used to sort only based on a single data member. Comparator can also be used when we want a sorting order other than the default sorting order of the class.

What happens when Comparator returns 0?

Java Comparator Interface Definition The semantics of the return values are: A negative value means that the first object was smaller than second object. The value 0 means the two objects are equal.

What is the Declaration of Comparator?

Method 2: Using comparator interface- Comparator interface is used to order the objects of a user-defined class. This interface is present in java. util package and contains 2 methods compare(Object obj1, Object obj2) and equals(Object element). Using a comparator, we can sort the elements based on data members.

What is difference between Comparator and comparable in Java?

Comparable in Java is an object to compare itself with another object, whereas Comparator is an object for comparing different objects of different classes. Comparable provides the compareTo() method to sort elements in Java, whereas Comparator provides compare() method to sort elements in Java.


1 Answers

The term ? super T means "unknown type that is, or is a super class of, T", which in generics parlance means its lower bound is T.

This signature is used because T may be assigned to, and compared with, any variable whose type is, or is a super class of, T. Ie if a Comparator can accept a super class of T in its compare() method, you can pass in a T.

This follows the PECS mnemonic: "Producer Extends, Consumer Super", which means that producers of things should work with things that have an upper bound ( ? extends T) and consumers (like comparator implementations that use things) should work with lower bounds ( ? super T).

like image 177
Bohemian Avatar answered Sep 28 '22 04:09

Bohemian