如何在列表中添加元素,而在Java迭代? [英] How to add element in List while iterating in java?

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

问题描述

说我有一个像列表:

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语句为。在fo​​reach使用内部迭代器:

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

此类的迭代器的ListIterator和返回的迭代器
  方法是快速失败的:如果列表结构的任何修改
  迭代器后时间被创建,以任何方式,除了通过
  迭代器自身的移除或添加方法,迭代器都将抛出
  ConcurrentModificationException的。

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语句你没有访问迭代器的添加方法,并在这仍然不是你想因为它没有在最后追加附加的类型的任何情况。你需要手动遍历列表:

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迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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