java - iterating a linked list

后端 未结 6 1064
半阙折子戏
半阙折子戏 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:50

    Linked list does guarantee sequential order.

    Don't use linkedList.get(i), especially inside a sequential loop since it defeats the purpose of having a linked list and will be inefficient code.

    Use ListIterator

        ListIterator iterator = myLinkedList.listIterator();
        while( iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    
        

    提交回复
    热议问题