为什么Collections.swap会复制输入列表? [英] Why does Collections.swap copy the input list?

查看:641
本文介绍了为什么Collections.swap会复制输入列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JDK1.6的源代码中,Collections类的swap方法如下所示:

In the source for JDK1.6, the Collections class' swap method is written like this:

public static void swap(List<?> list, int i, int j) {
    final List l = list;
    l.set(i, l.set(j, l.get(i)));
}

创建传递列表的最终副本的原因是什么?为什么他们不直接修改传递的列表?在这种情况下,您还会获得原始类型警告。

What reason is there for creating a final copy of the passed list? Why don't they simply modify the passed list directly? In this case, you also get the raw type warning.

推荐答案

没有列表的副本,只有一个副本对列表的引用。最终关键字并不重要。但是,使用原始类型很重要。如果使用该参数,编译器将报告错误:

There is no copy of the list, there is only a copy of the reference to the list. The final keyword is not important. However, it is important that a raw type is used. If the parameter would be used instead, the compiler would report an error:

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)));
}

这意味着,他们正在使用中间变量来规避泛型的缺点,并摆脱错误信息。

This means, that they are using the intermediate variable to circumvent the shortcomings of generics, and to get rid of the error message.

有趣的问题是:为什么他们不使用通用方法?以下代码有效:

The interesting question is: Why don't they use a generic method? The following code works:

public static <T> void swap(List<T> list, int i, int j) {
    list.set(i, list.set(j, list.get(i)));
}

答案是,此方法在旧代码中生成警告,调用方法原始类型:

The answer is, that this method produces warnings in old code invoking the method with raw types:

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);

这篇关于为什么Collections.swap会复制输入列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆