补充:这是 Java 1.7 - 正如其他人在 1.8 中指出的那样,它显然已修复
Collection<Collection<String>> xx;
// Fails
xx = Collections.singleton( Collections.singleton( "hello" ) );
// Succeeds
xx = Collections.singleton( (Collection<String>)Collections.singleton( "hello" ) )
-
Collections.singleton
返回Set<T>
在这种情况下Set<String>
-
Set<T> extends Collection<T>
编译器错误显示 Expected <Collection<Collection<String>> but found <Set<Set<String>>
但根据1和2我相信这应该满足。 successs 行上的强制转换似乎是多余的,为什么我需要提供它?
最佳答案
一个Collection<Collection<String>>
与 Collection<Set<String>>
不同(由 Collections.singleton()
返回)。编译器不会在没有显式强制转换的情况下自动转换这些内容(Java 8 上除外,这运行良好)。我相信您正在寻找的是
Collection<? extends Collection<String>> xx;
这将允许 xx
分配给任何Collection
其元素被声明为 Collection
的任何子类,包括 Collection
本身。
关于java - 没有显式强制转换的通用集合编译错误 - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25575085/