在Java中,您可以在迭代时修改List吗? [英] In Java, can you modify a List while iterating through it?

查看:103
本文介绍了在Java中,您可以在迭代时修改List吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,在Java中,迭代它时不应修改 Collection< E> ,例如删除或添加元素。但是如何更改List中的元素呢?例如,如果我们有

I understand that in Java a Collection<E> should not be modified while iterating through it, such as removing or adding elements. But what about changing the elements in a List? For example, what if we have

List<String> letters = new ArrayList<String>();
letters.add("A");
letters.add("B");
letters.add("C");
int i = 0;

for (String letter : letters) {
    letters.set(i, "D");
    i++;
}

所以,我不是在谈论修改存储在元素中的对象;我正在谈论改变对象是什么。 List的大小没有被更改,但索引处的对象正在改变,所以从技术上来说,List正在被修改。我的老板声称这段代码很好(而且看起来确实有效),但我仍然认为它不正确。使用ListIterator的set(E e)方法做一个不同的方法会更好吗?

So, I'm not talking about modifying the object stored at an element; I'm talking about changing what the object is. The size of the List is not being changed, but the object at the index is changing, so technically the List is being modified. My boss claims this code is fine (and it does appear to work), but I still don't think it is correct. Would a different way of doing it, maybe using the set(E e) method of a ListIterator, be better?

推荐答案

在遍历列表时修改列表中的元素的想法没有错(不要修改列表本身,这是不推荐的),但它可以更好地表达如下:

There is nothing wrong with the idea of modifying an element inside a list while traversing it (don't modify the list itself, that's not recommended), but it can be better expressed like this:

for (int i = 0; i < letters.size(); i++) {
    letters.set(i, "D");
}

最后,整个列表将包含字母 D作为其内容。在这种情况下,对于循环使用增强的并不是一个好主意,你没有使用迭代变量,除此之外你不能使用修改列表的内容迭代变量。

At the end the whole list will have the letter "D" as its content. It's not a good idea to use an enhanced for loop in this case, you're not using the iteration variable for anything, and besides you can't modify the list's contents using the iteration variable.

请注意,上面的代码片段修改列表的结构 - 意思是:没有添加或删除元素,列表'大小保持不变。简单地将一个元素替换为另一个元素并不算作结构修改。以下是@ zouZou在评论中引用的文档的链接,它声明:

Notice that the above snippet is not modifying the list's structure - meaning: no elements are added or removed and the lists' size remains constant. Simply replacing one element by another doesn't count as a structural modification. Here's the link to the documentation quoted by @ZouZou in the comments, it states that:


结构修改是添加或删除一个或多个元素或显式调整后备数组大小的任何操作;仅设置元素的值不是结构修改

A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification

这篇关于在Java中,您可以在迭代时修改List吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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