java - iterating a linked list

后端 未结 6 1065
半阙折子戏
半阙折子戏 2020-12-08 20:18

if I use a for-each loop on a linked list in java, is it guaranteed that I will iterate on the elements in the order in which they appear in the list?

6条回答
  •  天命终不由人
    2020-12-08 20:36

    As the definition of Linkedlist says, it is a sequence and you are guaranteed to get the elements in order.

    eg:

    import java.util.LinkedList;
    
    public class ForEachDemonstrater {
      public static void main(String args[]) {
        LinkedList pl = new LinkedList();
        pl.add('j');
        pl.add('a');
        pl.add('v');
        pl.add('a');
        for (char s : pl)
          System.out.print(s+"->");
      }
    }
    

提交回复
热议问题