我是编码的完全初学者。 我已经在这个论坛上寻找此问题的解决方案,但没有找到。
现在我一直在编写removeFirstNote()方法。
每次我尝试编译时都会收到一条错误消息:
java.util.-ConcurrentModificationException
这是我到目前为止所得到的...... 它需要通过 FOR-EACH 循环(学校任务)来完成。
public class Notebook
{
private ArrayList<String> notes;
public Notebook()
{
notes = new ArrayList<String>();
}
public void removeFirstNote(String certainString)
{ int noteNumber = 0;
boolean removed = false;
for (String note : notes){
if(note.contains(certainString) && !removed){
notes.remove(noteNumber);
removed = true;
} else {
noteNumber++;
}
}
}
最佳答案
您面临 ConcurrentModificationException
,因为您一次对同一个 列表
执行两个操作。即同时循环和删除。
为了避免这种情况,请使用迭代器,它可以保证您安全地从列表中删除元素。
Iterator<String> it = notes.iterator();
while (it.hasNext()) {
if (condition) {
it.remove();
break;
}
}
如果没有迭代器,
1)您需要使用另一个列表
2)将所有元素添加到其中。
3)在原始列表上循环
3)当条件满足时,从原始列表中
删除
关于java - 从 ArrayList 中删除某个字符串找到的第一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20239700/