Java 上下文:
类(class):Channel implements ICleanable
变量:Set<Channel> channels = new HashSet<>()
我需要使用 Iterable
数组调用此方法作为参数:
void unexport(Iterable<ICleanable>[] cleanables)
但我无法设计如何编写该调用。此版本不起作用:
unexport(new Iterable<ICleanable>[] { channels })
编译器说:“Type mismatch: cannot convert from Set<Channel> to Iterable<ICleanable>
”
我们将不胜感激(和/或引用学习 Material )。谢谢。
<小时/>编辑。现在我已经得到了答案,我可以总结一下我错在哪里。
我在泛型和子类型方面遇到了问题。这是一个初学者错误(这正是我的错误)。线索:
List<String> ls = new ArrayList<String>();
List<Object> lo = ls; // Illegal, a List<String> is not a List<Object>!
lo.add(new Object());
String s = ls.get(0); // Attempts to assign an Object to a String!
一个List<String>
不能 List<Object>
,否则类型安全无效。
这是解释here .
我在泛型数组方面遇到了第二个问题。
unexport(new Iterable<ICleanable>[] { channels })
无法创建 Iterable 数组。这是解释here 。类型转换错误导致编译器在纠正前一个错误之前无法检测到第二个错误。
就我而言,我最终得到的是:
void unexport(List<List<? extends ICleanable>> cleanables) {...}
Channel implements ICleanable;
List<Channel> channels = new ArrayList<>();
List<List<? extends ITVCleanable>> list = new ArrayList<>();
list.add(channels);
unexport(list);
最佳答案
您正在尝试创建 generic array在new Iterable<ICleanable>[]
。您无法直接创建通用数组,因此您可以这样做:
unexport((Iterable<ICleanable>[]) new Iterable[] { channels });
关于java - 类型不匹配 : cannot convert from Set<Channel> to Iterable<ICleanable>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25095831/