简体   繁体   中英

Correct way to declare a method with two type parameters in inheritance hierarchy

When writing a method that takes two objects, with two type parameters in a subtype-supertype relation, what is the best way of declaring your intentions out of these options?

  1. Declare both super and extends :

     public static <T> void copy(List<? super T> dst, List<? extends T> src) { ... } 
  2. Declare just the extends :

     public static <T> void copy(List<T> dst, List<? extends T> src) { ... } 
  3. Declare just the super :

     public static <T> void copy(List<? super T> dst, List<T> src) { ... } 

From my understanding, all three are correct, and are equivalent to each other, as all you're interested in is the relative inheritance of the type arguments of dst and src . So which is better?

I think extends is most common and if there is no need to use both you shouldn't. So I'd go with extends only.

So there is not a correct way, unless you have a convention that specifies it.

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