Cast element in Java For Each statement

前端 未结 5 2036
囚心锁ツ
囚心锁ツ 2021-02-19 00:30

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 <

5条回答
  •  爱一瞬间的悲伤
    2021-02-19 01:21

    For all the reasons stated by others, you shouldn't do this. However, if you cannot change the interface, the following is possible:

    for (BaseType element : list) {
        SubType subType = (SubType)element;
        ...
    }
    

    As far as I know, this is the only way to do this and remain truly type safe - i.e. not rely on type erasure to catch any problems, which it will not necessarily do until much later.

    I realize this is not EXACTLY what you were looking for, but it does handle the casting.

提交回复
热议问题