I have a superclass with a generic type extending a supertype (<E extends ...>
). This class has an abstract method that returns a list of the generic type.
Also I have a few subclasses implementing the abstract method.
When I call this method and try to replace objects in the list, the java compiler shows an error. I think the error is because my converting function returns a different capture of the type as it gets as parameter.
Here is a sample code using Exception as generic supertype:
import java.util.ArrayList;
import java.util.List;
public class GenericTest {
abstract class Super<E extends Exception>{
abstract List<E> foo();
}
class Sub1 extends Super<NullPointerException>{
@Override
List<NullPointerException> foo(){
return new ArrayList<NullPointerException>();
}
}
GenericTest(Super<? extends Exception> s){
List<? extends Exception> list = s.foo();
list.set(0, convertException(list.get(0)));
}
static <F extends Exception> F convertException(F exception){...}
}
There are two error occurs in the line
list.set(0, convertException(list.get(0)));
The compiler says for set
:
The method set(int, capture#2-of ? extends Exception) in the type List<capture#2-of ? extends Exception> is not applicable for the arguments (int, capture#3-of ? extends Exception)
and for convertException
:
Type mismatch: cannot convert from capture#3-of ? extends Exception to capture#2-of ? extends Exception
Why doesn't convertEException return the same capture#x
as it gets? It takes F and returns F.
Thanks for your help in advance!