Cast element in Java For Each statement

前端 未结 5 2034
囚心锁ツ
囚心锁ツ 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:16

    It is in fact possible to combine the cast with the for loop, like so:

    List list = DAO.getList();  
    for (SubType subType : ((List) list)){ 
        ...
    }
    

    Or you can use this slightly-cleaner pattern:

    List list = (List) DAO.getList();  
    for (SubType subType : list){ 
        ...
    }
    

    You will get an unchecked cast warning from the Java compiler, unless you suppress it. The effect of the first form will be effectively identical to casting each element within the loop. The second form will also enforce that new additions to the list must conform to SubType.

    Note that this will NOT work with arrays, since arrays have distinct runtime types. In other words, BaseType[] is not castable to SubType[]. You can use the Arrays API to work around this, like so:

    BaseType[] array = DAO.getArray();
    for (SubType subType : Arrays.asList(array)) {
        ...
    }
    

提交回复
热议问题