Casting between ArrayLists in Java

后端 未结 6 639
故里飘歌
故里飘歌 2020-12-15 11:56

Sorry, I thought this was an inheritance question: it was an ArrayList question all along!

Ok, my problem is more specific than I thought. So I have two families of

6条回答
  •  孤城傲影
    2020-12-15 12:41

    Marc and kolstae have given good answers in terms of how to get around the problem, but I think it's worth explaining why your original code doesn't work.

    To simplify matters, I tend to put the problem in terms of fruit. Suppose we have:

    List bananaBunch = new ArrayList();
    List fruitBowl = bananBunch;
    fruitBowl.add(new Apple());
    

    If this is allowed, we end up with an apple in a bunch of bananas, which is obviously a bad thing. So, where is the problem? The first line has to be okay, and the third line has to be okay - you can add any kind of fruit to List - so the problem has to be in the second line. That's what's prohibited, precisely to avoid this kind of issue.

    Does that help at all?

提交回复
热议问题