If type B can be generalised to type A, how do I convert a List<B> to a List<A>? Do I need a loop like:
List<A> newList=new ArrayList<A>();
for(B t:oldList) newList.add(t);
Edit: I don't know the word for it, but I mean to say an object of type B can be casted to an object of type A (like B implements A).
Edit2: It appears that the constructor also works:
List<A> newList=new ArrayList<A>(oldList);
However, I wanted a more efficient approach rather than just copying the list.
You shouldn't 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. Hence you shouldn't cast a List<B> into a List<A>.
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 );
As you stated in comments, If your Class B implements Class A, the below code is perfectly alight.
newList.addAll(listofBs);
Since every B is an A, you are allowed to do that.
And yes you need not to have a loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With