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 method getGenericList()
in thisDoesntWork()
.
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 a Class<E>
argument. Then you would invoke getGenericList(MyListElement.class)
in both thisWorks()
and thisDoesntWork()
. 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.
You can change thisDoesntWork()
like so:
public void thisDoesntWork(){ // well, it works now
myList.addAll(this.<String>getGenericList());
}
You need to tell the compiler what type getGenericList()
is dealing with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With