I have a question according to casting when generics in Java are used. I tried to provide a small example that explains my problem.
IVariable.java
public interface IVariable {
}
IProblem.java
public interface IProblem<V extends IVariable> {
}
Algorithm.java
public class Algorithm<V extends IVariable, P extends IProblem<V>> {
public void doSomething(P problem) {
// ERROR: Type mismatch: cannot convert from P to IProblem<IVariable>
IProblem<IVariable> genericProblem = problem;
}
}
Why do I need to cast the variable genericProblem explicitly to
@SuppressWarnings("unchecked")
IProblem<IVariable> genericProblem = (IProblem<IVariable>) problem;
and get a warning?
The method has P as an argument which is of type IProblem because V has to implement IVariable as well. Where is my mistake? What is the workaround?
I do not want to write
IProblem<V> genericProblem = problem;
because the input variable of the problem might be different.
Anyway in my opinion is IProblem<V>
more specific than IProblem<IVariable>
.
Thanks in advance!