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

问题描述

我知道在 Java 中,Collection 在遍历它时不应被修改,例如删除或添加元素.但是如何改变 List 中的元素呢?例如,如果我们有

List字母 = 新的 ArrayList();字母.add("A");字母.添加(B");字母.添加(C");int i = 0;for(字符串字母:字母){字母.set(i, "D");我++;}

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

解决方案

在遍历列表时修改列表中的元素的想法没有错(不要修改列表本身,不建议这样做),但它可以这样更好地表达:

for (int i = 0; i 

最后,整个列表将以字母 "D" 作为其内容.在这种情况下,使用增强的 for 循环不是一个好主意,您没有将迭代变量用于任何事情,而且您不能使用迭代变量修改列表的内容.>

注意上面的代码片段没有修改列表的结构——意思是:没有添加或删除元素,列表的大小保持不变.简单地用一个元素替换另一个元素不算作结构修改.这是@ZouZou 在评论中引用的文档的链接,它指出:

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

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++;
}

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");
}

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.

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:

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

08-23 17:24