在java中迭代时如何在List中添加元素? [英] How to add element in List while iterating in java?

查看:60
本文介绍了在java中迭代时如何在List中添加元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个列表:

List<String> list = new ArrayList<>();
list.add("a");
list.add("h");
list.add("f");
list.add("s");

在遍历此列表时,我想在列表末尾添加一个元素.但我不想遍历新添加的元素,我想迭代到列表的初始大小.

While iterating through this list I want to add an element at the end of the list. But I don't want to iterate through the newly added elements that is I want to iterate up to the initial size of the list.

for (String s : list)
     /* Here I want to add new element if needed while iterating */

有人可以建议我怎么做吗?

Can anybody suggest me how can I do this?

推荐答案

您不能为此使用 foreach 语句.foreach 在内部使用迭代器:

You can't use a foreach statement for that. The foreach is using internally an iterator:

该类的迭代器和listIterator返回的迭代器方法是快速失败的:如果列表在任何时候在结构上被修改迭代器创建后的时间,以任何方式,除了通过迭代器自己的 remove 或 add 方法,迭代器会抛出一个并发修改异常.

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

(来自 ArrayList javadoc)

(From ArrayList javadoc)

在 foreach 语句中,您无权访问迭代器的 add 方法,并且无论如何这仍然不是您想要的 add 类型,因为它不会在末尾追加.您需要手动遍历列表:

In the foreach statement you don't have access to the iterator's add method and in any case that's still not the type of add that you want because it does not append at the end. You'll need to traverse the list manually:

int listSize = list.size();
for(int i = 0; i < listSize; ++i)
  list.add("whatever");

请注意,这仅对允许随机访问的列表有效.您可以通过检查列表是否实现 RandomAccess 标记接口来检查此功能.ArrayList 具有随机访问权限.链表没有.

Note that this is only efficient for Lists that allow random access. You can check for this feature by checking whether the list implements the RandomAccess marker interface. An ArrayList has random access. A linked list does not.

这篇关于在java中迭代时如何在List中添加元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆