For example, lets say you have two classes:
public class TestA {}
public class TestB extends TestA{}
I have a method that returns a List<TestA>
and I would like to cast all the objects in that list to TestB
so that I end up with a List<TestB>
.
Simply casting to
List<TestB>
almost works; but it doesn't work because you can't cast a generic type of one parameter to another. However, you can cast through an intermediate wildcard type and it will be allowed (since you can cast to and from wildcard types, just with an unchecked warning):You really can't*:
Example is taken from this Java tutorial
Assume there are two types
A
andB
such thatB extends A
. Then the following code is correct:The previous code is valid because
B
is a subclass ofA
. Now, what happens withList<A>
andList<B>
?It turns out that
List<B>
is not a subclass ofList<A>
therefore we cannot writeFurthermore, we can't even write
*: To make the casting possible we need a common parent for both
List<A>
andList<B>
:List<?>
for example. The following is valid:You will, however, get a warning. You can suppress it by adding
@SuppressWarnings("unchecked")
to your method.You cannot cast
List<TestB>
toList<TestA>
as Steve Kuo mentions BUT you can dump the contents ofList<TestA>
intoList<TestB>
. Try the following:I've not tried this code so there are probably mistakes but the idea is that it should iterate through the data object adding the elements (TestB objects) into the List. I hope that works for you.
With Java 8, you actually can