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

后端 未结 7 862
时光说笑
时光说笑 2020-11-29 13:01

I have the following class & interface defined:

public interface A {
}

public class B implements A {
}

I have a List of <

相关标签:
7条回答
  • 2020-11-29 13:28

    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 and now contains a C even though you have specified that it shouldn't.

    0 讨论(0)
提交回复
热议问题