2016-01-15 163 views
1

我在使用Java中的泛型时遇到了铸造问题。 我试图提供一个小例子来解释我的问题。Java泛型在接口之间铸造

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; 

    } 

} 

为什么我需要明确地投下变量genericProblem到

@SuppressWarnings("unchecked") 
IProblem<IVariable> genericProblem = (IProblem<IVariable>) problem; 

并得到警告?

该方法将P作为类型IProblem的参数,因为V也必须实现IVariable。 我的错误在哪里?什么是解决方法?

我不想写

IProblem<V> genericProblem = problem; 

因为问题的输入变量可能会有所不同。 无论如何,在我看来,IProblem<V>IProblem<IVariable>更具体。

在此先感谢!

回答

2

IProblem<V>并不等同于一个IProblem<IVariable>,即使V被constrainted是一个IVariable,因为Java的泛型是不变的。当然,IProblem<V>是要走的路,但如果你不想这样,你可以使用上界通配符来表达VIVariable之间的关系,而不是:

IProblem<? extends IVariable> genericProblem = problem; 
1

的泛型类型必须是一个完全符合。 V extends IVariableIVariable不是可互换的类型。让我举另一个例子。

List<Integer> ints = new ArrayList<>(); // list of ints. 
List<Number> nums = ints; // doesn't compile but this is what you are trying to do 
nums.add(new BigDecimal(0.0)); // fine as BigDecimal is a Number.