Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does self comparable interface do in Collections Class?

While practicing Reflection I came to know about SelfComparable Interface in Collections class

interface java.util.Collections$SelfComparable

What does this interface use for ?

like image 699
Prateek Avatar asked Sep 05 '13 10:09

Prateek


People also ask

What is the purpose of comparable interface?

The Comparable interface is used to compare an object of the same class with an instance of that class, it provides ordering of data for objects of the user-defined class. The class has to implement the java.

What are the benefits of implementing the Comparable interface?

The benefit of implementing the interface is that some methods specifically require object that implements the Comparable interface. It gives them a guarantee that the object you're passing has a compareTo method with the correct signature.

How does Comparable interface work in Java?

Java Comparable interface is used to order the objects of the user-defined class. This interface is found in java. lang package and contains only one method named compareTo(Object). It provides a single sorting sequence only, i.e., you can sort the elements on the basis of single data member only.

What is the use of Comparator and comparable in Java?

Comparator in Java is used to sort attributes of different objects. Comparable interface compares “this” reference with the object specified. Comparator in Java compares two different class objects provided. Comparable is present in java.


2 Answers

It doesn't do anything. It is private so you can't import it.

It is really a comment that the type is "SelfComparable" and is not actually used.

Nothing implement this interface. The code which uses it relies on the fact it will be discarded at runtime.

public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) {
    if (comp==null)
        return (T)max((Collection<SelfComparable>) (Collection) coll);

could have been

public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) {
    if (comp==null)
        return (T)max(/*SelfComparable*/ (Collection) coll);

as it will be ignored at runtime.

like image 62
Peter Lawrey Avatar answered Sep 19 '22 00:09

Peter Lawrey


From source:

private interface SelfComparable extends Comparable<SelfComparable> {}

This is nothing more than a marker over Comparable<SelfComparable>, which basically means that it is a marker for comparables that compare to self. Its use is somewhat superfluous.

It's used as:

return (T)min((Collection<SelfComparable>) (Collection) coll);

on line 662 where it basically casts a collection to Collection, and then performs a cast for the generic parameter to be a SelfComparable which just extends Comparable.

like image 44
nanofarad Avatar answered Sep 20 '22 00:09

nanofarad