Using Java 6 SE, I have a class that contains a Vector. There is a class method that simply calls the contained Vector’s addAll() method with the same parameters for each. The Vectors can be of either type “Superclass” or type “Subclass” and I want the addAll() methods to support both. This whole setup might look like this:
public class VectorAContainer(){
this.vectorA = new Vector<Superclass>();
}
public void addAll(Vector<Superclass> vector){
this.vectorA.addAll(vector);
}
Then I want to call a line of code like this:
VectorAContainer container = new VectorAContainer();
container.addAll(vectorB); //where vectorB is a Vector<Subclass>
The problem is, Eclipse gives the following error:
“The method addAll(Vector<Superclass>) in the type
VectorAContainer is not applicable for the arguments
(Vector<Subclass>).”
Strangely, I have found that addAll() works if it’s NOT inside of a class:
//No container with an addAll(), calling directly on vectorA
this.vectorA.addAll(vectorB); //No errors!
I don’t see a difference between the two above cases. I would like to get the first way to work because I have a much more elaborate class that contains a Vector like the one above. I would greatly appreciate any help you all could provide!
You need to accept a covariant generic parameter:
You can see this in the declaration of
addAll: