9/27/2016 - 11:32 AM

Java >> List cast

Java >> List cast

Class B inherits from class A. 
You shouldn't cast List<B> to List<A> since List<B> means that it will contain only elements of type B or subtypes. List<A> would allow you to add elements of type A as well, which might be dangerous.

If you create a new List<A> and put all elements of List<B> into it (e.g. using a loop possibly wrapped in a method) it's ok.

One simple way to fill a new list would be the addAll() method, e.g.

List<A> aList = ...;
List<B> bList = ...;

aList.addAll( bList );