D
dugrocker
Hi,
I've got a super class A and A subclass of A called B. I want to make a
collection that can be created as either a collection of A or a
subclass of A. That is fine, and seems to compile fine.
However, when I actually make a collection that contains a subclass of
A (B in this example), I cannot add elements of B to the collection.
Does anyone know the solution?
Code snippet below:
<code>
package generics;
import java.util.ArrayList;
public class MyContainer
{
ArrayList<? extends A> bList; //The list should be a list of
something
//that either extends or
is an A. B
//Fullfills this
requirement
MyContainer()
{
bList = new ArrayList<B>();//List of child class B (compiles)
}
public static void main(String[] args)
{
MyContainer myContainer = new MyContainer();
/* *********************************************************
* The problem is here in the next line.
*
* Compiler message:
*
* The method add(capture-of ? extends A) in the type
* ArrayList<capture-of ? extends A> is not applicable for the
* arguments (B)
*
* *********************************************************/
myContainer.bList.add(new B()); //(fails to compile)
}
}
</code>
I've got a super class A and A subclass of A called B. I want to make a
collection that can be created as either a collection of A or a
subclass of A. That is fine, and seems to compile fine.
However, when I actually make a collection that contains a subclass of
A (B in this example), I cannot add elements of B to the collection.
Does anyone know the solution?
Code snippet below:
<code>
package generics;
import java.util.ArrayList;
public class MyContainer
{
ArrayList<? extends A> bList; //The list should be a list of
something
//that either extends or
is an A. B
//Fullfills this
requirement
MyContainer()
{
bList = new ArrayList<B>();//List of child class B (compiles)
}
public static void main(String[] args)
{
MyContainer myContainer = new MyContainer();
/* *********************************************************
* The problem is here in the next line.
*
* Compiler message:
*
* The method add(capture-of ? extends A) in the type
* ArrayList<capture-of ? extends A> is not applicable for the
* arguments (B)
*
* *********************************************************/
myContainer.bList.add(new B()); //(fails to compile)
}
}
</code>