Java中的Cast元素对于每个语句 [英] Cast element in Java For Each statement

查看:150
本文介绍了Java中的Cast元素对于每个语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可能(或甚至是明智的)将从for语句中检索的元素强制转换为语句本身中的每个语句?我知道列表中的每个元素将是< SubType>

Is it possible (or even advisable) to cast the element retrieved from a for each statement in the statement itself? I do know that each element in list will be of type <SubType>.

IE:

List<BaseType> list = DAO.getList();  
for(<SubType> element : list){ 
    // Cannot convert from element type <BaseType> to <SubType>
    ...
}

而不是:

List <BaseType> list = DAO.getList();
for(<BaseType> el : list){
    <SubType> element = (<SubType>)el;
    ...
}


推荐答案

你真的知道每个条目都是一个子类型吗? DAO只需要满足 List< BaseType> 契约,如果你假设一个子类,那么我认为某处出错了。我可能更专注于获得DAO的接口正确,并有合同返回你想要的。

Do you really know that each entry is going to be a subtype ? The DAO simply has to fulfill the List<BaseType> contract, and if you're assuming a subclass, then I think something is wrong somewhere. I'd perhaps concentrate more on getting the interface to the DAO correct, and have it contractually return what you want.

这篇关于Java中的Cast元素对于每个语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆