Reputation: 20575
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!
Upvotes: 0
Views: 676
Reputation: 23
It's because Superclass is a lower bound annotation meaning classes that are Super to Vector. If vectorB is a subclass to Vector then it won't work. AbstractList and AbstractCollection are Super to Vector. I believe you want to use.
public void addAll(Vector<? extends Vector> vector){
vectorA.addAll(vector);
}
P.S. Vector is an obsolete class. You should use ArrayList if you don't need a thread safe implementation.
*P.P.S. You don't need to use "this" unless you have two variables with the same name (e.g.
private Variable variableA;
public void example(Variable variableA){
this.variableA = variableA;
}
Upvotes: 0
Reputation: 887365
You need to accept a covariant generic parameter:
public void addAll(Collection<? extends Superclass> c)
You can see this in the declaration of addAll
:
boolean addAll(Collection<? extends E> c)
Upvotes: 2