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?
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With