且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在列表中添加元素,而在Java迭代?

更新时间:2022-11-28 13:12:35

您不能使用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.