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

后端 未结 7 968
时光说笑
时光说笑 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

    Rather than fighting against a language feature, you should learn to use it properly.

    Rather than asking how to use unsafe casts to work around the error, it is instructive to first understand why there's an error; why what you're asking to do is unsafe (because you can add an A to the list using listA and then take it out of the list as a B using listB).

    Then, you should explain why you think that your use case does not run into the unsafe scenario. Because the answer to this will give a hint for how to change your code to make it work correctly with generics.

    • If you say that it is not unsafe because you never add anything using listA, then you should change the type of listA to List. That way, you can assign listB to it directly without any casts, and you won't be able to add anything to it using listA (except null).
    • If you say that it is not unsafe because you never get anything out using listB, then why not change the type of listB to List in the first place?

提交回复
热议问题