Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Casting from List<B> to List<A> when B implements A?

I have the following class & interface defined:

public interface A {
}

public class B implements A {
}

I have a List of B objects that I need to cast to a List of A objects:

List<B> listB = new List<B>();
listB.add(new B());  // dummy data
listB.add(new B());  // dummy data
listB.add(new B()); // dummy data

List<A> listA = (List<A>) listB;

The last line above results in compile error "Cannot cast from List<B> to List<A>". I attempted to work around this with this following instead:

List<A> listA = Arrays.asList((A[]) listB.toArray());

Unfortunately, that throws a ClassCastException. Does anyone know how I can resolve this?

like image 852
Matt Huggins Avatar asked Nov 27 '22 01:11

Matt Huggins


1 Answers

You cannot cast it like that. Create a new one:

List<A> listA = new ArrayList<A>(listB);

The constructor takes Collection<? extends A>. It will point to the same references anyway.

like image 52
BalusC Avatar answered Dec 04 '22 21:12

BalusC