Why is SomeClass<? super T> not equivalent to SomeClass in Java generic types?

后端 未结 5 632
清酒与你
清酒与你 2020-12-08 23:52

I noticed the specificaition for Collections.sort:

public static  void sort(List list, Comparator c)

Why

5条回答
  •  甜味超标
    2020-12-09 00:40

    The simple answer to your question is that the library designer wanted to give the maximum flexibility to the user of the library; this method signature for example allows you to do something like this:

    List ints = Arrays.asList(1,2,3);
    Comparator numberComparator = ...;
    
    Collections.sort(ints, numberComparator);
    

    Using the wildcard prevents you from being forced to use a Comparator; the fact that the language requires a wildcard to be specified by the library designer enables him or her to either permit or restrict such use.

提交回复
热议问题