EquilateralTriangle
is a subtype of Triangle
.
List<? super EquilateralTriangle> equilateralTriangle =
new ArrayList<Triangle>(Arrays.asList(new Triangle(), new Triangle()));
equilateralTriangle.add(new Triangle()); // doesn't work
equilateralTriangle.add(new EquilateralTriangle()); // works
As far as I know List<? super EquilateralTriangle>
is the declaration and with new ArrayList<Triangle>
we are telling something concrete to the compiler that my arraylist is of type triangle. Then why does compiler complain on the second line? I'm inserting the same value as I defined in the type parameter defined while instantiating arraylist.
Java arraylist definition says this:
class ArrayList<E> extends AbstractList<E>
public ArrayList(Collection<? extends E> c)
and boolean add(E e);
for ArrayList
.
So, the type E
can be infered as Triangle
. Then add
must not complain as I'm passing the Triangle
as I did in ArrayList
constructor. What is missing in my understanding?