Carl Summers Carl Summers - 2 years ago 117
Java Question

Cast element in Java For Each statement

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



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

rather than:

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download