Java:迭代迭代对象的属性 [英] Java: Changing the properties of an iterable object while iterating over it
本文介绍了Java:迭代迭代对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码只是为了产生一个问题的示例:
The following code is just to produce an example of the problem:
public static void main(String[] args) {
Collection<Integer> src = new ArrayList<Integer>();
Collection<Integer> dest = new ArrayList<Integer>();
src.add(2);
src.add(7);
src.add(3);
src.add(2201);
src.add(-21);
dest.add(10);
while (src.size() != 0) {
for (int i : dest) {
int min = Collections.min(src);
dest.add(min);
src.remove(min);
}
}
}
我是什么我想做的是按照特定顺序将所有内容从src移动到dest。 (这里,它是最小值,但这只是我真正问题的简化。)但是,我在迭代它时修改dest,并得到以下错误:
What I want to do is move everything from src to dest in a specific order. (Here, it's what is the minimum value, but that's just a simplification from my real problem.) However, I am modifying dest while iterating over it, and get the following error:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at nth23.experimental.MoveBetweenSets.main(MoveBetweenSets.java:25)
我该如何解决这个问题?
How can I get around this?
推荐答案
这是一种解决方法:
while (!src.isEmpty()) {
int min = Collections.min(src);
dest.add(min);
src.remove(min);
}
但这可能会让事情变得更糟。更具体一点(如Jon所说)。
But this might be even make thing worse. Be a bit more specific (as Jon mentioned).
这篇关于Java:迭代迭代对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文