Carl Summers Carl Summers - 1 year ago 76
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;


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.