Ways to iterate over a list in Java

后端 未结 12 1831
孤独总比滥情好
孤独总比滥情好 2020-11-22 00:46

Being somewhat new to the Java language I\'m trying to familiarize myself with all the ways (or at least the non-pathological ones) that one might iterate through a list (or

12条回答
  •  醉话见心
    2020-11-22 01:16

    I don't know what you consider pathological, but let me provide some alternatives you could have not seen before:

    List sl= list ;
    while( ! sl.empty() ) {
        E element= sl.get(0) ;
        .....
        sl= sl.subList(1,sl.size());
    }
    

    Or its recursive version:

    void visit(List list) {
        if( list.isEmpty() ) return;
        E element= list.get(0) ;
        ....
        visit(list.subList(1,list.size()));
    }
    

    Also, a recursive version of the classical for(int i=0... :

    void visit(List list,int pos) {
        if( pos >= list.size() ) return;
        E element= list.get(pos) ;
        ....
        visit(list,pos+1);
    }
    

    I mention them because you are "somewhat new to Java" and this could be interesting.

提交回复
热议问题