<T> void copy(List<? extends T> src, List<? super T> dest) {
if (src == null || dest == null || src.size() != dest.size()){
throw new IllegalArgumentException();
}
for (int i = 0; i < src.size(); i++) {
dest.set(i, src.get(i));
}
}
PECS : Producer Extends, Consumer Super
- "Producer Extends" - If you need a List to produce T values (you want to read Ts from the list), you
need to declare it with ? extends T, e.g. List<? extends Integer>. But you cannot add to this
list.
- "Consumer Super" - If you need a List to consume T values (you want to write Ts into the list), you need
to declare it with ? super T, e.g. List<? super Integer>. But there are no guarantees what type of
object you may read from this list.
- If you need to both read from and write to a list, you need to declare it exactly with no wildcards,
e.g. List<Integer>.