tags:

views:

142

answers:

2

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));
+4  A: 

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.

Andrzej Doyle
A: 

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.

Kathy Van Stone