javagenerics

Why does generics in java collections so strange?


For example check method in java.util.Collections

 public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) 

Why can I define it this way:

 public static <T> int binarySearch(List<T> list, T key, Comparator<T> c) 

Why does this will not work in java?


Solution

  • You could define it that way, but then that wouldn't let you search a List<Circle> using a Comparator<Shape>, for example.

    Basically, the variance being expressed here allow for more flexibility while maintaining type safety.