Java Generics Casting between Interfaces -
this question has answer here:
i have question according casting when generics in java used. tried provide small example explains 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 p iproblem<ivariable> iproblem<ivariable> genericproblem = problem; } } why need cast variable genericproblem explicitly
@suppresswarnings("unchecked") iproblem<ivariable> genericproblem = (iproblem<ivariable>) problem; and warning?
the method has p argument of type iproblem because v has implement ivariable well. mistake? workaround?
i not want write
iproblem<v> genericproblem = problem; because input variable of problem might different. anyway in opinion iproblem<v> more specific iproblem<ivariable>.
thanks in advance!
an iproblem<v> not equivalent iproblem<ivariable>, if v constrainted ivariable, because java's generics invariant. sure, iproblem<v> way go, if don't want that, can use upper-bounded wildcard express relationship between v , ivariable instead:
iproblem<? extends ivariable> genericproblem = problem;
Comments
Post a Comment