Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ArrayList<String> to ArrayList<Object>

Tags:

java

generics

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.

like image 470
user1537366 Avatar asked Dec 18 '25 04:12

user1537366


2 Answers

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 );
like image 170
Thomas Avatar answered Dec 20 '25 18:12

Thomas


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.

like image 36
Suresh Atta Avatar answered Dec 20 '25 17:12

Suresh Atta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!