使用 Java 6 SE,我有一个包含 Vector 的类。有一个类方法可以简单地调用包含的 Vector 的 addAll() 方法,每个方法都使用相同的参数。 vector 可以是“父类(super class)”类型或“子类”类型,我希望 addAll() 方法支持这两种类型。整个设置可能如下所示:
public class VectorAContainer(){
this.vectorA = new Vector<Superclass>();
}
public void addAll(Vector<Superclass> vector){
this.vectorA.addAll(vector);
}
然后我想调用这样的一行代码:
VectorAContainer container = new VectorAContainer();
container.addAll(vectorB); //where vectorB is a Vector<Subclass>
问题是,Eclipse 给出以下错误:
"The method addAll(Vector<Superclass>) in the type VectorAContainer is not applicable for the arguments (Vector<Subclass>)."
奇怪的是,我发现如果 addAll() 不在类内部,它就可以工作:
//No container with an addAll(), calling directly on vectorA
this.vectorA.addAll(vectorB); //No errors!
我不认为上述两种情况有什么区别。我想获得第一种工作方式,因为我有一个更复杂的类,其中包含一个像上面那样的 vector 。我将非常感谢你们提供的任何帮助!
最佳答案
您需要接受协变泛型参数:
public void addAll(Collection<? extends Superclass> c)
您可以在 declaration of addAll
中看到这一点:
boolean addAll(Collection<? extends E> c)
关于java - 当 Vector 位于包含类中时,使用 Vector 的 addAll( ) 函数时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8640238/