2013-07-26

How to cast a List of Objects to another type in Java

For example, if you have:
class Father{}
class Son extends Father{}
Now you're going to do like:
void doSomething(List<Father> list){}
doSomething(new ArrayList<Son>());
This won't work because you can't cast a generic type of one parameter to another. Java will give to you compile error.
Solution is to use wildcard type:
void doSomething(List<?> list){
  List<Parent> parents = (List<Parent>)list;

No comments: