简体   繁体   中英

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?

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.

To amplify Jon Skeet 's answer a bit, Java's generics are not like C++ templates. Some of the design decisions (like the type erasure) for generics, made for backward compatibility of the JVM itself, lead to awkward syntax and complicated use cases. You can read about some of these here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM