I’m having some problems with a method returning a generic list. The code is basically this:
public class MyClass{
private List<MyListElement> myList = new ArrayList<MyListElement>();
public <E> List<E> getGenericList(){
return new ArrayList<E>();
}
public void thisWorks(){
List<MyListElement> newList = getGenericList();
myList.addAll(newList);
}
public void thisDoesntWork(){
myList.addAll(getGenericList());
}
public void thisDoesntWorkEither(){
for(MyListElement elem : getGenericList()){
fiddle();
}
}
}
Why does the thisDoesntWork() method not work, and is there any other way around it (other than doing it the thisWorks() way which isn’t always practical)?
The compiler cannot infer what type to choose for the type parameter
<E>of the generic methodgetGenericList()inthisDoesntWork().In this case you need to explicitly state the Type for the type argument by calling
<MyListElement>getGenericList()Alternatively you can change the signature of
getGenericList()to accept aClass<E>argument. Then you would invokegetGenericList(MyListElement.class)in boththisWorks()andthisDoesntWork(). Admittedly that’s a bit more verbose, but definitly more intuitive to clients of your method.I would say as a general rule, try to make the type arguments of your generic methods be inferrable from that method’s arguments.