Vahan
Vahan

Reputation: 3268

How to convert list of generic subtypes to list of specific subtype?

Suppose class B extends class A and we have

List<? extends A> list1;
List<B> list2;

Is there a way to assign list1 to lsit2 without running through all elements?

Upvotes: 0

Views: 69

Answers (2)

Selaron
Selaron

Reputation: 6184

List<B> list2 = (List<B>)list1;

You will have to deal with compiler warning and possibly ClassCastExceptions when getting Elements from list2.

Upvotes: 1

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

Simply put, no.

The reason is that the compiler doesn't have any evidence that the runtime types of the list1 elements will be B (or any subtype of B). They could be of type C extends A, which could lead to ClassCastExceptions at Runtime.

However, you can always traverse through the list1 and add all the elements to list2 by doing casts (only if you're confident that the types are compatible, of course). Even though it would work, however, is a sign of a bad design.

Upvotes: 0

Related Questions