What does a comparable interface do in a collection class?

While I was engaged in reflection, I learned about the SelfComparable Interface in the Collections class

 interface java.util.Collections$SelfComparable 

What is this interface used for?

+6
source share
2 answers

It does nothing. This is personal, so you cannot import it.

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

Nothing implements this interface. The code that uses it relies on it to 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.

+7
source

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 comparisons of comparisons with itself. Its use is somewhat redundant.

Used as:

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

to line 662 , where it basically drops the collection into Collection , and then casts to the generic parameter as SelfComparable , which simply continues to Comparable .

+2
source

Source: https://habr.com/ru/post/953230/


All Articles