3

我正在尝试使用列表迭代器从列表中删除一个对象。我已经浏览了网站上的其他解决方案,但没有一个可以缓解错误“线程“主”java.util.ConcurrentModificationException 中的异常”

这是我没有执行的代码:

void PatronReturn(String bookName) {
//       get to beginning
    while(listIterator.hasPrevious()) {
        listIterator.previous();
    }
    while(listIterator.hasNext()){
        Book b = listIterator.next();
    if (listIterator.next().getBookTitle().equals(bookName)) { 
        //listIterator.next();
        //listIterator.remove();
        books.remove(b);
        //listIterator.next(); //moves to next so iterator can remove previous ?
        //books.remove(listIterator.next());; // TODO see if this is correct

    }
    }
4

6 回答 6

11
  1. 不要直接从列表中删除项目。使用remove()迭代器中的方法。

  2. 您的代码也存在缺陷,因为它假定还有其他列表项:

    while(listIterator.hasNext()){
        Book b = listIterator.next();
        if (listIterator.next().getBookTitle().equals(bookName)) { 
          // eek
    

    在这里你调用next()了两次,但你只调用了hasNext一次。也许你的意思是:

    while(listIterator.hasNext()){
        Book b = listIterator.next();
        if (b.getBookTitle().equals(bookName)) { 
          // ...
    
  3. 最后,您可以替换:

    while(listIterator.hasPrevious()) {
        listIterator.previous();
    }
    

    listIterator = books.listIterator();
    
于 2013-04-18T13:31:01.563 回答
5

而不是 books.remove(b)

利用

listIterator.remove();

原因是,迭代器给你 next() 书,如果你只从书中删除这本书,迭代器将“删除”的书仍然作为下一本书。

它在您的代码中不起作用,因为您调用了 .next() 两次,一次是针对书 b,第二次是在比较书名和下一本书时。

于 2013-04-18T13:32:01.723 回答
0
{   Book toBeReaplced = null; Book tempBook = null;   
void PatronReturn(String bookName)           
{//       get to beginning
while(listIterator.hasPrevious()) {        listIterator.previous();
}
while(listIterator.hasNext()){
    Book tempBook = listIterator.next();
if (b.getBookTitle().equals(bookName)) { 
             toBeReaplced = tempBook;

}

listIterator.remove(bookToBeReplaced);
}

你可以试试上面的代码。我认为它能够解决您的问题,即您遇到了 java.util.ConcurrentModificationException" 错误。有关错误的更多参考,请点击链接

于 2013-04-18T13:51:24.317 回答
0

代替 books.remove(b)

尝试使用

   listIterator.remove();
于 2013-04-18T13:33:33.183 回答
0

您不能ArrayList在迭代时删除项目。

你可以:

  • ListIterator使用(每个 next() 最多一次)的 remove() 方法
  • 使用另一种List实现,例如CopyOnWriteArrayList,保证永远不会抛出ConcurrentModificationException,但这在您的情况下可能是矫枉过正。
于 2013-04-18T13:36:02.033 回答
0

您不能在迭代列表时删除项目,您应该使用 .remove()

还要删除这个:

while(listIterator.hasPrevious()) {
    listIterator.previous();
}

这不是必需的

于 2013-04-18T13:36:47.943 回答