This is because ArrayList<E>
is not covariant on the type E
. That is, you cannot substitute an instance of ArrayList<Derived>
for ArrayList<Base>
just because Derived
inherits from Base
.
Consider this case: String
inherits from Object
; however, if this meant you could use an ArrayList<String>
as an ArrayList<Object>
then the following code would be possible:
ArrayList<Object> list = new ArrayList<String>();
list.add(new Integer(5)); // Integer inherits from Object
The above can't work, because you can't add an Integer
to an ArrayList<String>
. If you could, then this could happen:
ArrayList<String> stringList = (ArrayList<String>)list;
String string = stringList.get(0); // Not a string!
As Ziyao has indicated, the correct way to implement this is to use the ? extends Edge
syntax.