gpt4 book ai didi

java - 为什么迭代比随机访问更可取

转载 作者:行者123 更新时间:2023-12-02 06:22:01 25 4
gpt4 key购买 nike

The following page

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

这是什么意思?这是否意味着我应该更喜欢

ListIterator<Integer> iterator = list.listIterator(0);
iterator.next()
iterator.next()

超过

list.get(1)

如果是这样,为什么?如果底层列表实现是普通数组,则 get 将在恒定时间内执行。但使用迭代器它是O(n)。我在这里缺少什么?

他们是否意味着我应该使用list.listIterator(1);而不是list.get(1)

最佳答案

没有。但你应该更喜欢

for (Integer value : list) {
// do something with value
}

(或显式使用列表迭代器的循环)

超过

for (int i = 0; i < list.size(); i++) {
Integer value = list.get(i);
// do something with value
}

如果列表是链表,则第一个列表的复杂度为 O(N),第二个列表的复杂度为 O(N^2)。事实上,在每次迭代时,它都需要遍历列表(从开始或结束,取决于i的值),直到到达第i位置。当您使用迭代器或 foreach 循环时,不会发生这种情况。

另一个很好的理由是,在并发列表的情况下,迭代器可以是一致的(即在创建迭代器时创建的列表的一致快照上进行迭代)。使用列表索引的迭代不会出现这种情况。

关于java - 为什么迭代比随机访问更可取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43895242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com