【发布时间】:2018-10-01 07:25:21
【问题描述】:
我正在尝试在 for 循环中自动将对象列表的每个元素转换为正确的类型
class A {
}
class B {
void sampleMethod() {
List<?> l1 = //initialized somewhere;
/*
I do know perfectly l1 got elements of Class A
I just could not declare List<A> for other (generic types) reasons
*/
for (A el: l1) { // Type mismatch: cannot convert from element type capture#1-of ? to A
System.out.println(el);
}
}
}
正如我在代码中发布的那样,“for 语句”显示错误:
类型不匹配:无法从元素类型 capture#1-of 转换?到A
我尝试过其他解决方案,例如:
for (A el: (List<A>)l1)
这会导致警告:
类型安全:从 List 到 List 的未经检查的强制转换
最后我找到了一个可行的(但在我看来并不合适)的解决方案,即在 for: 中进行转换:
for (Object el: l1) {
A listEl = (A) el;
System.out.println(el);
}
为什么我不能在 for 语句中进行这种类型的转换?真的没有办法干净利落吗?
【问题讨论】:
-
List<? extends A>工作吗? -
你不能使用
List<Object>有什么原因吗? -
@ShanuGupta 效果很好!对我来说很有意义!谢谢!!