Why are generics in java collections so weird?

For example, the validation 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 as follows:

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

Why does this not work in java?

+4
source share
2 answers

You can define it this way, but then it will not let you search for a List<Circle> with a Comparator<Shape> , for example.

Basically, the variance expressed here provides greater flexibility while maintaining type safety.

+14
source

To enhance Jon Skeet , answer a bit, Java generics are not like C ++ templates. Some design decisions (such as type wiping) for generics made for backward compatibility of the JVM itself lead to inconvenient syntax and complex use cases. You can read about some of them here.

0
source

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


All Articles