【发布时间】:2011-01-21 08:51:27
【问题描述】:
public static void someMethod(List < ? extends BaseDto > list) {
for (ChildDto dto : list) {
}
}
ChildDto 扩展了 BaseDto,在这里我确定它的列表中充满了 ChildDto。
我知道我可以做这样的事情
for (TextApplicationDto dto : (List<TextApplicationDto>)list) {
但它看起来并不漂亮。
有没有更好的铸造方法?
【问题讨论】:
-
在我看来,它不漂亮是有好处的——你应该避免强制转换,因为它们会使你的代码不那么安全。当演员表看起来很丑时,您就不太愿意使用它。
-
恕我直言,你不应该这样投。这样的演员阵容产生警告是有充分理由的。像 gabuzo 建议的那样做对我来说看起来好多了。
标签: java generics casting coding-style