我认为我在编写代码时犯了一些错误。 我有一个实现接口(interface)的类 MyClass,现在我有一个接口(interface)列表通用的方法作为参数。我想通过传递一个列表来使用我的方法。我不能从一个列表转换到另一个列表(我以为我可以)。那么,我该怎么做才能使我的代码正常工作?这里有一个例子:
List<MyClass> lista = returnMyClassList();
myMethod((List<Interface>) lista); //this doesn't work
//myMethod signature
public void myMethod(List<Interface> struttura);
感谢您的帮助。
最佳答案
使用上限 Interface
对于类型:<? extends Interface>
.
下面是使用 JDK 中的类进行说明的可编译代码:
public static void myMethod(List<? extends Comparable> struttura) {}
public static void main(String[] args) {
List<Integer> lista = null;
myMethod(lista); // compiles OK
}
关于java - 从 List<MyClass> 转换为 List<Interface>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18851504/