java - 迭代链表
如果我在java中的链表上使用for-each循环, 是否保证我会按顺序迭代元素 它们出现在哪个列表中?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我发现了 5 种在 Java 中迭代链表的主要方法(包括 Java 8 方法):
For循环
增强的for循环
While循环
Iterator
collection stream() util (Java 8)
需要指出的是,For Loop 或 While 的运行时间循环的时间复杂度为 O(n 平方),因为
get(i)
操作需要 O(n) 时间(有关详细信息,请参阅此)。其他 3 种方式需要线性时间并且性能更好。I found 5 main ways to iterate over a Linked List in Java (including the Java 8 way):
For loop
Enhanced for loop
While loop
Iterator
collection stream() util (Java 8)
One thing should be pointed out is that the running time of For Loop or While Loop is O(n square) because
get(i)
operation takes O(n) time(see this for details). The other 3 ways take linear time and performs better.链表保证按顺序执行。
来自文档
迭代器()
按正确顺序返回此列表中元素的迭代器。
Linked list is guaranteed to act in sequential order.
From the documentation
iterator()
Returns an iterator over the elements in this list in proper sequence.
正如 Linkedlist 的定义所示,它是一个序列,并且保证您按顺序获取元素。
例如:
As the definition of Linkedlist says, it is a sequence and you are guaranteed to get the elements in order.
eg:
链表确实保证顺序。
不要使用 linkedList.get(i),尤其是在顺序循环内,因为它违背了链表的目的,并且代码效率低下。
使用ListIterator
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
每个 java.util.List 实现都需要保留顺序,因此您可以使用 ArrayList、LinkedList、Vector 等。它们中的每一个都是有序集合,并且它们中的每一个都保留插入的顺序(请参阅 http://download.oracle.com/javase/1.4.2/docs/ api/java/util/List.html)
Each java.util.List implementation is required to preserve the order so either you are using ArrayList, LinkedList, Vector, etc. each of them are ordered collections and each of them preserve the order of insertion (see http://download.oracle.com/javase/1.4.2/docs/api/java/util/List.html)
为未来的访问者添加我的输入。
首先要做的事情:按照 $jls-14.14.2,for-each内部使用迭代器。
现在,当您使用for-遍历LinkedList时every 或迭代器,则循环始终是顺序的。
但这样很容易出现线程安全问题。因此,可能会发生两件事:
ConcurrentModificationException
CopyOnWriteArrayList
这样的线程安全 List 实现。如果您必须使用LinkedList
,则只能使用Collections.synchronizedList()
将非线程安全LL转换为线程安全LL,但您再次需要注意使用以线程安全的方式迭代器。Adding my inputs for future visitors.
First things first: as per $jls-14.14.2, for-each internally use Iterator.
Now, when you iterate over LinkedList using a for-each or an iterator then the looping is always sequential.
But this is prone to thread safety issues. So, two things can happen:
ConcurrentModificationException
CopyOnWriteArrayList
. And if you must use aLinkedList
only then useCollections.synchronizedList()
to convert your non-threadsafe LL into a threadsafe LL, but again you need to watch out for using iterator in a threadsafe manner.