Possible Duplicate:
Most efficient way to cast List<SubClass> to List<BaseClass>
why polymorphism doesn't treat generic collections and plain arrays the same way?
If I have an abstract base class BaseClass and I write a function expecting Collection<BaseClass> as its argument, calls to that function with a Collection<SubClass> of a class SubClass extends BaseClass fail to compile.
In the base class:
public void addLots(Collection<BaseClass> collection) {
for(BaseClass yourbase : collection) {
us.add(yourbase) //what you say!!
}
}
And in the subclass:
public void addMoreLots(Collection<SubClass> collection) {
addLots(collection); //FAILS TO COMPILE
}
Now I think I can see why this is: Collection<SubClass> is NOT a subclass of Collection<BaseClass>. What is the correct method of making this call?
Collectionsare checked only during the compilation time,notduring the run time, so this is done in order to protect a collection taking in the wrong type of object in.Try it this way…
public <T extends BaseClass> void addLots(Collection<T> collection){ }OR
public void addLots(Collection<? extends BaseClass> collection) {}