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?
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.
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