简体   繁体   中英

Java generics, copy one list to another

I have these two function signatures in java, which is supposed to copy the list src to the list dst:

1. public static <T> void copy1(List<T> dst, List<? extends T> src)
2. public static <T> void copy2(List<? super T> dst, List<? extends T> src)

The question is if there is a difference between the two function signatures,and if there are cases in which the second option will work, and the first one won't.

To answer your first question, are these two function signatures different in java? No ! The quickest way to test this is by calling them both copy and verifying that the compiler complains of duplicate methods.

public static <T> void copy(List<T> dst, List<? extends T> src)
public static <T> void copy(List<? super T> dst, List<? extends T> src)

Your second question is, in what case would one work and the other wouldn't?

Well essentially we're talking about the first parameter, dst since it is the only difference between the two.

For any given T, in the case of copy2, the first parameter would have to a superclass of T or T itself and the second parameter would have to a subclass of T or T itself. The compiler interprets to mean that the first parameter generic type must be T, and the second parameter generic type is simply an extension of T. In fact, if you try, you'll see that the compiler will only take the same type as generic of first parameter or a derived class of that:

public static <T> void copy2(List<? super T> dst, List<? extends T> src) {
    // Copy
}

public static void main(String[] args) {
    List<Number> dst = new ArrayList<Number>();
    List<Integer> src = getSource();

    copy2(dst, src);  // Works when 2nd generic param type subclass of 1st
    copy2(dst, dst);  // Works when 2nd generic param type same as 1st
    copy2(src, dst);  // Invalid types for method!
}

Rather in the case of copy1, the first parameter is T, and the second parameter is still just the subclass of T. So we're talking about the same scenario here. In this context, there is no situation in which one would work and the other would not.

public static <T> void copy1(List<T> dst, List<? extends T> src) {
    // Copy
}

public static void main(String[] args) {
    List<Number> dst = new ArrayList<Number>();
    List<Integer> src = getSource();

    copy1(dst, src);  // Works when 2nd generic param type subclass of 1st
    copy1(dst, dst);  // Works when 2nd generic param type same as 1st
    copy1(src, dst);  // Invalid types for method!
}

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