Cast element in Java For Each statement

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

    If you are not partial to Google collections, you can wrap the list with transform method. In your case it will be very efficient and totally compliant. I would put it as a wrapper method though as Brian has suggested.

    public List< SubType > fromDao ( )
    {
        // Put a comment for maintainer
    
        // Lists from DAO always contain SubTypes
        return
            Lists.transform(
                DAO.getList( ),
                new Function< BaseType, SubType >( )
                {
                    public SubType apply ( final BaseType from )
                    {
                        return (SybType) from;
                    }
                };
    }
    

提交回复
热议问题