Reputation: 47514
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>
.
Upvotes: 315
Views: 363929
Reputation: 6686
You can use the selectInstancesOf
method in Eclipse Collections. This will involved creating a new collection however so will not be as efficient as the accepted solution which uses casting.
List<CharSequence> parent =
Arrays.asList("1","2","3", new StringBuffer("4"));
List<String> strings =
Lists.adapt(parent).selectInstancesOf(String.class);
Assert.assertEquals(Arrays.asList("1","2","3"), strings);
I included StringBuffer
in the example to show that selectInstancesOf
not only downcasts the type, but will also filter if the collection contains mixed types.
Note: I am a committer for Eclipse Collections.
Upvotes: 2
Reputation: 101
I had to do this implementation in a method of the company's system:
interface MyInterface{}
Class MyClass implements MyInterface{}
The method receives an interface list, that is, I already have an interface list instantiated
private get(List<MyInterface> interface) {
List<MyClass> myClasses = interface.stream()
.filter(MyClass.class::isInstance)
.map(MyClass.class::cast)
.collect(Collectors.toList());
}
Upvotes: 0
Reputation: 308
Simple answer
You can't directly type cast.
Workaround
public <T> List<T> getSubItemList(List<IAdapterImage> superList, Class<T> clazz) {
return superList.stream()
.map(item -> clazz.isInstance(item) ? clazz.cast(item) : null)
.collect(Collectors.toList());
}
Usage
private final List<IAdapterImage> myList = new ArrayList<>();
List<SubType> subTypeList = getSubItemList(myList,SubType.class);
So this is simple workaround I use to convert my list with super type into list with subtype. We are using stream api which was introduced in java 8 here, using map on our super list we are simply checking if passed argument is instance of our super type the returning the item. At last we are collecting into a new list. Of course we have to get result into a new list here.
Upvotes: 0
Reputation: 61986
Casting a List of supertypes to a List of subtypes is nonsensical and nobody should be attempting or even contemplating doing such a thing. If you think your code needs to do this, you need to rewrite your code so that it does not need to do this.
Most visitors to this question are likely to want to do the opposite, which does actually make sense:
The best way I have found is as follows:
List<TestA> testAs = List.copyOf( testBs );
This has the following advantages:
List.of()
!!!If you look at the source code of List.copyOf()
you will see that it works as follows:
List.of()
, then it will do the cast and return it without copying it.ArrayList()
,) it will create a copy and return it.If your List<TestB>
is an ArrayList<TestB>
then a copy of the ArrayList
must be made. If you were to cast the ArrayList<TestB>
as List<TestA>
, you would be opening up the possibility of inadvertently adding a TestA
into that List<TestA>
, which would then cause your original ArrayList<TestB>
to contain a TestA
among the TestB
s, which is memory corruption: attempting to iterate all the TestB
s in the original ArrayList<TestB>
would throw a ClassCastException
.
On the other hand, if your List<TestB>
has been created using List.of()
, then it is unchangeable(*1), so nobody can inadvertently add a TestA
to it, so it is okay to just cast it to List<TestA>
.
(*1) when these lists were first introduced they were called "immutable"; later they realized that it is wrong to call them immutable, because a collection cannot be immutable, since it cannot vouch for the immutability of the elements that it contains; so they changed the documentation to call them "unmodifiable" instead; however, "unmodifiable" already had a meaning before these lists were introduced, and it meant "an unmodifiable to you view of my list which I am still free to mutate as I please, and the mutations will be very visible to you". So, neither immutable or unmodifiable is correct. I like to call them "superficially immutable" in the sense that they are not deeply immutable, but that may ruffle some feathers, so I just called them "unchangeable" as a compromise.
Upvotes: 7
Reputation: 6453
Casting of generics is not possible, but if you define the list in another way it is possible to store TestB
in it:
List<? extends TestA> myList = new ArrayList<TestA>();
You still have type checking to do when you are using the objects in the list.
Upvotes: 127
Reputation: 2035
class MyClass {
String field;
MyClass(String field) {
this.field = field;
}
}
@Test
public void testTypeCast() {
List<Object> objectList = Arrays.asList(new MyClass("1"), new MyClass("2"));
Class<MyClass> clazz = MyClass.class;
List<MyClass> myClassList = objectList.stream()
.map(clazz::cast)
.collect(Collectors.toList());
assertEquals(objectList.size(), myClassList.size());
assertEquals(objectList, myClassList);
}
This test shows how to cast List<Object>
to List<MyClass>
. But you need to take an attention to that objectList
must contain instances of the same type as MyClass
. And this example can be considered when List<T>
is used. For this purpose get field Class<T> clazz
in constructor and use it instead of MyClass.class
.
UPDATED
Actually you can't cast from supertype to subtype in strong typed Java AFAIK. But you can introduce an interface that the supertype implements.
interface ITest {
}
class TestA implements ITest {
}
class TestB extends TestA {
}
public class Main {
public static void main(String[] args) {
List<ITest> testAList = Arrays.asList(new TestA(), new TestA());
Class<ITest> clazz = ITest.class;
List<ITest> testBList = testAList.stream()
.map(clazz::cast)
.collect(Collectors.toList());
System.out.println(testBList.size());
System.out.println(testAList);
}
}
Or you can cast from subtype to supertype. Like this:
class TestA {
}
class TestB extends TestA {
}
public class Main {
public static void main(String[] args) {
var a = new TestA();
var b = new TestB();
System.out.println(((TestA) b));
List<TestB> testBList = Arrays.asList(new TestB(), new TestB());
Class<TestA> clazz = TestA.class;
List<TestA> testAList = testBList.stream()
.map(clazz::cast)
.collect(Collectors.toList());
System.out.println(testAList.size());
System.out.println(testAList);
}
}
FYI my original answer pointed on a possibility of using it with generics
. In fact I took it from my Hibernate DAO code.
Upvotes: 1
Reputation: 3745
Quite strange that manually casting a list is still not provided by some tool box implementing something like:
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T extends E, E> List<T> cast(List<E> list) {
return (List) list;
}
Of course, this won't check items one by one, but that is precisely what we want to avoid here, if we well know that our implementation only provides the sub-type.
Upvotes: 1
Reputation: 63084
You really can't*:
Example is taken from this Java tutorial
Assume there are two types A
and B
such that B extends A
.
Then the following code is correct:
B b = new B();
A a = b;
The previous code is valid because B
is a subclass of A
.
Now, what happens with List<A>
and List<B>
?
It turns out that List<B>
is not a subclass of List<A>
therefore we cannot write
List<B> b = new ArrayList<>();
List<A> a = b; // error, List<B> is not of type List<A>
Furthermore, we can't even write
List<B> b = new ArrayList<>();
List<A> a = (List<A>)b; // error, List<B> is not of type List<A>
*: To make the casting possible we need a common parent for both List<A>
and List<B>
: List<?>
for example. The following is valid:
List<B> b = new ArrayList<>();
List<?> t = (List<B>)b;
List<A> a = (List<A>)t;
You will, however, get a warning. You can suppress it by adding @SuppressWarnings("unchecked")
to your method.
Upvotes: 50
Reputation: 109
This should would work
List<TestA> testAList = new ArrayList<>();
List<TestB> testBList = new ArrayList<>()
testAList.addAll(new ArrayList<>(testBList));
Upvotes: -1
Reputation: 62769
The problem is that your method does NOT return a list of TestA if it contains a TestB, so what if it was correctly typed? Then this cast:
class TestA{};
class TestB extends TestA{};
List<? extends TestA> listA;
List<TestB> listB = (List<TestB>) listA;
works about as well as you could hope for (Eclipse warns you of an unchecked cast which is exactly what you are doing, so meh). So can you use this to solve your problem? Actually you can because of this:
List<TestA> badlist = null; // Actually contains TestBs, as specified
List<? extends TestA> talist = badlist; // Umm, works
List<TextB> tblist = (List<TestB>)talist; // TADA!
Exactly what you asked for, right? or to be really exact:
List<TestB> tblist = (List<TestB>)(List<? extends TestA>) badlist;
seems to compile just fine for me.
Upvotes: 1
Reputation: 54639
Since this is a widely referenced question, and the current answers mainly explain why it does not work (or propose hacky, dangerous solutions that I would never ever like to see in production code), I think it is appropriate to add another answer, showing the pitfalls, and a possible solution.
The reason why this does not work in general has already been pointed out in other answers: Whether or not the conversion is actually valid depends on the types of the objects that are contained in the original list. When there are objects in the list whose type is not of type TestB
, but of a different subclass of TestA
, then the cast is not valid.
Of course, the casts may be valid. You sometimes have information about the types that is not available for the compiler. In these cases, it is possible to cast the lists, but in general, it is not recommended:
One could either...
The implications of the first approach (which corresponds to the currently accepted answer) are subtle. It might seem to work properly at the first glance. But if there are wrong types in the input list, then a ClassCastException
will be thrown, maybe at a completely different location in the code, and it may be hard to debug this and to find out where the wrong element slipped into the list. The worst problem is that someone might even add the invalid elements after the list has been casted, making debugging even more difficult.
The problem of debugging these spurious ClassCastExceptions
can be alleviated with the Collections#checkedCollection
family of methods.
A more type-safe way of converting from a List<Supertype>
to a List<Subtype>
is to actually filter the list, and create a new list that contains only elements that have certain type. There are some degrees of freedom for the implementation of such a method (e.g. regarding the treatment of null
entries), but one possible implementation may look like this:
/**
* Filter the given list, and create a new list that only contains
* the elements that are (subtypes) of the class c
*
* @param listA The input list
* @param c The class to filter for
* @return The filtered list
*/
private static <T> List<T> filter(List<?> listA, Class<T> c)
{
List<T> listB = new ArrayList<T>();
for (Object a : listA)
{
if (c.isInstance(a))
{
listB.add(c.cast(a));
}
}
return listB;
}
This method can be used in order to filter arbitrary lists (not only with a given Subtype-Supertype relationship regarding the type parameters), as in this example:
// A list of type "List<Number>" that actually
// contains Integer, Double and Float values
List<Number> mixedNumbers =
new ArrayList<Number>(Arrays.asList(12, 3.4, 5.6f, 78));
// Filter the list, and create a list that contains
// only the Integer values:
List<Integer> integers = filter(mixedNumbers, Integer.class);
System.out.println(integers); // Prints [12, 78]
Upvotes: 12
Reputation: 21249
With Java 8, you actually can
List<TestB> variable = collectionOfListA
.stream()
.map(e -> (TestB) e)
.collect(Collectors.toList());
Upvotes: 56
Reputation: 122439
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):
List<TestB> variable = (List<TestB>)(List<?>) collectionOfListA;
Upvotes: 676
Reputation: 715
The best safe way is to implement an AbstractList
and cast items in implementation. I created ListUtil
helper class:
public class ListUtil
{
public static <TCastTo, TCastFrom extends TCastTo> List<TCastTo> convert(final List<TCastFrom> list)
{
return new AbstractList<TCastTo>() {
@Override
public TCastTo get(int i)
{
return list.get(i);
}
@Override
public int size()
{
return list.size();
}
};
}
public static <TCastTo, TCastFrom> List<TCastTo> cast(final List<TCastFrom> list)
{
return new AbstractList<TCastTo>() {
@Override
public TCastTo get(int i)
{
return (TCastTo)list.get(i);
}
@Override
public int size()
{
return list.size();
}
};
}
}
You can use cast
method to blindly cast objects in list and convert
method for safe casting.
Example:
void test(List<TestA> listA, List<TestB> listB)
{
List<TestB> castedB = ListUtil.cast(listA); // all items are blindly casted
List<TestB> convertedB = ListUtil.<TestB, TestA>convert(listA); // wrong cause TestA does not extend TestB
List<TestA> convertedA = ListUtil.<TestA, TestB>convert(listB); // OK all items are safely casted
}
Upvotes: 7
Reputation: 59
The only way I know is by copying:
List<TestB> list = new ArrayList<TestB> (
Arrays.asList (
testAList.toArray(new TestB[0])
)
);
Upvotes: 5
Reputation: 533492
When you cast an object reference you are just casting the type of the reference, not the type of the object. casting won't change the actual type of the object.
Java doesn't have implicit rules for converting Object types. (Unlike primitives)
Instead you need to provide how to convert one type to another and call it manually.
public class TestA {}
public class TestB extends TestA{
TestB(TestA testA) {
// build a TestB from a TestA
}
}
List<TestA> result = ....
List<TestB> data = new List<TestB>();
for(TestA testA : result) {
data.add(new TestB(testA));
}
This is more verbose than in a language with direct support, but it works and you shouldn't need to do this very often.
Upvotes: 4
Reputation: 2487
You cannot cast List<TestB>
to List<TestA>
as Steve Kuo mentions BUT you can dump the contents of List<TestA>
into List<TestB>
. Try the following:
List<TestA> result = new List<TestA>();
List<TestB> data = new List<TestB>();
result.addAll(data);
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.
Upvotes: 9
Reputation: 16534
if you have an object of the class TestA
, you can't cast it to TestB
. every TestB
is a TestA
, but not the other way.
in the following code:
TestA a = new TestA();
TestB b = (TestB) a;
the second line would throw a ClassCastException
.
you can only cast a TestA
reference if the object itself is TestB
. for example:
TestA a = new TestB();
TestB b = (TestB) a;
so, you may not always cast a list of TestA
to a list of TestB
.
Upvotes: 2
Reputation: 6089
This is possible due to type erasure. You will find that
List<TestA> x = new ArrayList<TestA>();
List<TestB> y = new ArrayList<TestB>();
x.getClass().equals(y.getClass()); // true
Internally both lists are of type List<Object>
. For that reason you can't cast one to the other - there is nothing to cast.
Upvotes: 1
Reputation: 20121
I think you are casting in the wrong direction though... if the method returns a list of TestA
objects, then it really isn't safe to cast them to TestB
.
Basically you are asking the compiler to let you perform TestB
operations on a type TestA
that does not support them.
Upvotes: 20