Bal*_*sky 2 java iteration optimization
迭代元素列表是很常见的.检查一些条件并从列表中删除一些元素.
for (ChildClass childItem : parent.getChildList()) {
if (childItem.isRemoveCandidat()) {
parent.getChildList().remove(childItem);
}
}
Run Code Online (Sandbox Code Playgroud)
但在这种情况下抛出java.util.ConcurrentModificationException.
在这种情况下,最好的程序模式是什么?
dac*_*cwe 11
用一个Iterator.如果您的列表支持,Iterator.remove您可以使用它!它不会抛出异常.
Iteartor<ChildClass> it = parent.getChildList().iterator();
while (it.hasNext())
if (it.next().isRemoveCandidat())
it.remove();
Run Code Online (Sandbox Code Playgroud)
注意:ConcurrentModificationException当你"开始"迭代一个集合并在迭代期间修改列表时抛出(例如在你的情况下,它没有任何与并发相关的东西.你List.remove在迭代期间使用该操作,那就是同样在这种情况下..).
public static void main(String[] args) {
List<Integer> list = new LinkedList<Integer>();
list.add(1);
list.add(2);
list.add(3);
for (Iterator<Integer> it = list.iterator(); it.hasNext(); )
if (it.next().equals(2))
it.remove();
System.out.println(list); // prints "[1, 3]"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
266 次 |
| 最近记录: |