gpt4 book ai didi

接口(interface)之间的 Java 泛型转换

转载 作者:行者123 更新时间:2023-11-29 04:52:42 24 4
gpt4 key购买 nike

<分区>

当使用 Java 中的泛型时,我有一个关于转换的问题。我试图提供一个小例子来解释我的问题。

IVariable.java

public interface IVariable {
}

问题.java

public interface IProblem<V extends IVariable> {
}

算法.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> 更具体.

提前致谢!

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com