没有列表的副本,只有列表引用的副本。最终关键字并不重要。然而,使用原始类型很重要。如果改用该参数,编译器会报告错误:
public static void swap(List<?> list, int i, int j) {
// ERROR: The method set(int, capture#3-of ?) in the type List<capture#3-of ?>
// is not applicable for the arguments (int, capture#4-of ?)
list.set(i, list.set(j, list.get(i)));
}
这意味着,他们使用中间变量来规避泛型的缺点,并消除错误消息。
有趣的问题是:为什么他们不使用通用方法?以下代码有效:
public static <T> void swap(List<T> list, int i, int j) {
list.set(i, list.set(j, list.get(i)));
}
答案是,此方法会在使用原始类型调用该方法的旧代码中产生警告:
List list = ...;
// WARNING: Type safety: Unchecked invocation swap2(List, int, int)
// of the generic method swap2(List<T>, int, int) of type Swap
Collections.swap(list, 0, 1);