开发者

Doubt with List<Generic> Explicit Cast

开发者 https://www.devze.com 2022-12-08 07:14 出处:网络
I don\'t understand why in some cases I can make an explicit cast and in other cases I can not. Thanks to all!

I don't understand why in some cases I can make an explicit cast and in other cases I can not. Thanks to all!

//DAreaLabel extends Message 

//This Code Works
List<Message> list1 = (List<Message>)
        Arrays.开发者_运维问答asList((Message[]) getPageRecords(getClasspath(), methodName, object));

DAreaLabel areaLabel = (DAreaLabel)
        ((List<Message>) Arrays.asList((Message[]) getPageRecords(getClasspath(), methodName, object))).get(0);

//This Code does not Work
List<DAreaLabel> list2 = (List<DAreaLabel>)
        Arrays.asList((Message[]) getPageRecords(getClasspath(), methodName, object));


Your latter cast doesn't work, essentially because generics are not covariant.

That is, assuming DAreaLabel is a subtype of Message, then you can cast a Message into a DAreaLabel, but you cannot cast a List<Message> into a List<DAreaLabel>, which is effectively what you are trying to do in the latter case.


Even though DAreaLabel is (presumably) a subclass of Message, List<DAreaLabel> is not a subclass of List<Message>. The Java Tutorial's generics trail says why. Thus the last case does not compile. The first case also should not need casting at all.


You should be able to cast a List<Message> into a List<? extends Message>, which could then reference a List<DAreaLabel>. However, instances retrieved would still need to be cast to DAreaLabel to use that class's features.

0

精彩评论

暂无评论...
验证码 换一张
取 消