2

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.

2
  • You mean like B extends A ? Commented Sep 10, 2015 at 7:31
  • @sᴜʀᴇsʜᴀᴛᴛᴀ My use case was when B implements A. Commented Sep 10, 2015 at 7:32

5 Answers 5

4

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 );
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

Generics does not allow you to directly up cast collection objects.

You can do couple of things:

List<B> oldList = new List<B>();
List<? super B> upcastedList = oldList; // No new object created.

If you need to cast the list to a specific type (say A), then you have no option than to loop every element and add it to new list (as you have specified in the question).

Comments

1

If you are OK with listA being unmodifiable, here's another possible answer (using Ankur's hint):

List<B> listB=new ArrayList<B>();
List<A> listA=Collections.unmodifiableList((List<? extends A>)listB);

Comments

1

It could be added during creation as well like

List<A> newList = new ArrayList<A>(oldList);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.