Implementations and Collections

后端 未结 4 1825
北海茫月
北海茫月 2020-12-21 12:24

Why does this not work...

public ArrayList getEdges() {

return A;

//A is an Arraylist of type \'Action\'. Action implements Ed         


        
4条回答
  •  情歌与酒
    2020-12-21 13:08

    This is because ArrayList is not covariant on the type E. That is, you cannot substitute an instance of ArrayList for ArrayList just because Derived inherits from Base.

    Consider this case: String inherits from Object; however, if this meant you could use an ArrayList as an ArrayList then the following code would be possible:

    ArrayList list = new ArrayList();
    list.add(new Integer(5)); // Integer inherits from Object
    
    
    

    The above can't work, because you can't add an Integer to an ArrayList. If you could, then this could happen:

    ArrayList stringList = (ArrayList)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.

    提交回复
    热议问题