Java 泛型集合
我在Java 泛型集合,java,Java,我在java.util.Collections中有一个关于此方法的问题: public class Collections { public static <T> void copy(List<? super T> dest, List<? extends T> src) { for (int i=0; i<src.size();i++) dest.set(i,src.get(i)); } }
java.util.Collections
中有一个关于此方法的问题:
public class Collections {
public static <T> void copy(List<? super T> dest, List<? extends T> src) {
for (int i=0; i<src.size();i++)
dest.set(i,src.get(i));
}
}
公共类集合{
公共静态无效拷贝(list < P>不),这是有意义的。例如,考虑这种情况:
T
是InputStream
dest
是一个列表
src
是一个列表
当然,在这种情况下,您可以使T
成为Object
或FileInputStream
,但假设您是从签名为的方法调用它的:
public void doSomething(List<? super InputStream> streams) {
// I want to use copy in here for some reason
}
public void doSomething(List如果您将其细分为使用该列表的原因,它将更加清晰
当一个方法打算填充一个列表时,您可以将其限制为使用特定的类型T,但通常您可能希望限制更少
例如,假设您有一个方法populateWithStudents(List)
您有Student-extend-Person
这意味着,即使Student扩展了Person,也不能将该方法与列表一起使用来填充Student对象
因此,如果另一方面我们想允许,我们将其更改为populateWithStudents(列表OK,很好的解释)。非常感谢。