Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 311
yura Avatar asked Dec 09 '22 12:12

yura


1 Answers

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.

like image 96
Jon Skeet Avatar answered Dec 21 '22 10:12

Jon Skeet