类型不匹配:无法从Set <channel>转换为Iterable <icleanable> </icleanable> </channel>

时间:2014-08-02 14:01:31

标签: java generics interface parameter-passing type-mismatch

Java上下文:

班级: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>

将不胜感激(和/或参考学习材料)。感谢。


EDIT。现在我已经得到了答案,我可以总结出错的地方。

我遇到了泛型和子类型的问题。这是一个初学者错误(这正是我所说的)。线索:

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);

1 个答案:

答案 0 :(得分:1)

您正试图在new Iterable<ICleanable>[]创建generic array。您无法直接创建通用数组,因此您可以这样做:

unexport((Iterable<ICleanable>[]) new Iterable[] { channels });