views:

90

answers:

4

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?

+7  A: 

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.

BalusC
+1  A: 

I'm sure you need make the whole list List< A >(weird parsing there) and when adding new B objects cast them with (A)

listA.add( (A) new B());  // dummy data
Adam
+2  A: 

You can just use type erasure if you know the operation is safe. This produces a warning which you can turn off using @SuppressWarnings

List<A> listA = (List) listB;

The reason the compiler has difficulty with a plain cast is that you can now add a class C which also implements A. Except your original list has been altered which not contains a C even though you have specified that it shouldn't.

Peter Lawrey
+1  A: 
List<A> listA = (List<A>)(List<?>) listB;

not recommended.

irreputable