简体   繁体   中英

Define bounded type parameter in method type parameter list or in method argument

what's the difference between the following two method definitions? Which one is preferred if they are the same?

public static <T extends Comparable<? super T>>
void sort1(List<T> list) {}

public static <T>
void sort2(List<? extends Comparable<? super T>> list) {}

And if the methods have more then one parameter that uses the type parameter, what's the difference then?

public static <T extends Comparable<? super T>>
void add1(List<T> list, T element) {}

public static <T>
void add2(List<? extends Comparable<? super T>> list, T element) {}

These are not identical; for the type system, they are different. sort1 accepts a List of a type variable and sort2 accepts a List of a wildcard . Since you are doing a sort operation, that will modify the incoming parameter (the List ); you might want to do this internally, for example:

public static <T extends Comparable<? super T>> void sort1(List<T> list) {
    list.set(0, list.get(0));
}

public static <T> void sort2(List<? extends Comparable<? super T>> list) {
    list.set(0, list.get(0)); // does not compile
}

only to find out that the second will not compile, because it uses a wildcard (there are ways to work-around this, though).

The same exact situation will arise in your second example, if you try to do:

public static <T> void add2(List<? extends Comparable<? super T>> list, T element) {
    list.add(element);
}

The general rule is that when you try to modify , you want to stick with type variables. If you can't do that, there are ways to work-around it, like wildcard capture , for example.

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