An ArrayList<B> not an ArrayList<A> . For example, you cannot add an arbitrary A . Or how I like to think about it: a bunch of bananas is not a fruit. When you try to add an apple to a bunch of bananas, it rolls back ...
You can use wildcards to make it work:
public ArrayList<? extends A> foo() { return new ArrayList<B>(); }
See the Java Generics FAQ for more details.
EDIT: To answer your specific question, why you need to write all this extra code, you do not. Just create an ArrayList<A> inside foo() to start. There is no need to copy the contents of one list to another.
If you still mind Java behavior, what would you like to do with the following code?
source share