Java ListIterator 性能

标签 java list iterator linked-list

我正在读一篇thread这里介绍一下java ArrayList和LinkedList的性能。有来自Mr Kevin Brock的答复内容如下。

"Linked list add is not always O(1) [or this should say addLast() is O(1)]. This is only true if done from within a ListIterator. The add methods in Java's LinkList implementation must search through the list if additions are not on the head or tail."

我不明白他所说的“仅当通过ListIterator完成”是什么意思。这是否意味着链表中有一个数据结构保存每个索引的引用,一旦我们从某个索引获取列表迭代器,列表迭代器就会立即返回,而无需遍历列表来查找该索引?

谢谢大家!

最佳答案

表示迭代器直接指向列表节点;因此通过 get(int) 访问的时间复杂度为 O(N),但 iterator.next() 的访问时间复杂度为 O(1)。后者有直接引用,不需要遍历任何东西;前者需要从列表的头部开始遍历。

关于Java ListIterator 性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4423381/

相关文章:

java - 在 JBoss Drools 中表达条件

python - 子类化 Python 列表以验证新项目

c# - 如何在 List<object> 中搜索具有其字段值的对象

python - 使用 yield 而不是 return 创建函数以连续从 http 流生成帧

java - 抛出子异常,捕获为 super 异常并重新抛出它但声明抛出子异常

java - 解析没有分隔符的基于周的年份和基于周的年份失败

java - Apache Beam 使用多个表时有多少写入次数

python - 如何在python中的两个值之间选择一个列表 block

c++ - 使用迭代器在字符串中查找子字符串

c++ - 迭代器后继