使用Java中的步骤迭代LinkedList(Iterating LinkedList with steps in Java)

编程入门 行业动态 更新时间:2024-10-23 14:25:10
使用Java中的步骤迭代LinkedList(Iterating LinkedList with steps in Java)

想象一下,我们知道列表的大小,并希望只浏览其中的每个第五个元素。 我想如果我用ArrayList做到这一点,如下所示:

List<Item> l = new ArrayList<Item>(); for (int i = 0; i < l.size(); ) { Item item = l.get(i); i += 5; }

每当我调用l.get(i)这是愚蠢的时候,它会间接遍历列表中的每个元素。 有没有办法只访问每五个元素? 也许LinkedList ? 能否请您举例说明如何将ListIterator用于此目的?

Imagine we know the size of the list and want to go through every fifth element in it only. I think if I do that with ArrayList, like below:

List<Item> l = new ArrayList<Item>(); for (int i = 0; i < l.size(); ) { Item item = l.get(i); i += 5; }

it will indirectly iterate through every element of the list up to i each time I call l.get(i) which is stupid. Is there any way to access only every fifth element? Maybe LinkedList? Could you please give me an example on how to use the ListIterator for that purpose?

最满意答案

每次调用l.get(i)时,它会间接遍历列表中的每个元素。

不,不会。 get(i)在ArrayList是一个O(1)操作,将直接从后备数组中获取项目 - 不涉及迭代。 请参阅ArrayList的javadoc :

size,isEmpty,get,set,iterator和listIterator操作以恒定时间运行。


相反,如果你使用LinkedList ,它将迭代每个元素,效率会降低,如LinkedList javadoc中所述 :

索引到列表中的操作将从开头或结尾遍历列表,以较接近指定索引为准。

it will indirectly iterate through every element of the list up to i each time I call l.get(i)

No it won't. get(i) in ArrayList is an O(1) operation and will fetch the item directly from the backing array - no iteration involved. See the ArrayList's javadoc:

The size, isEmpty, get, set, iterator, and listIterator operations run in constant time.


On the contrary, if you use a LinkedList, it will iterate through every element and it will be less efficient, as explained in the LinkedList javadoc:

Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.

更多推荐

本文发布于:2023-07-29 20:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1319407.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:步骤   迭代   Java   steps   Iterating

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!