尝试使用列表迭代器删除对象

我正在尝试使用列表迭代器从列表中删除对象。 我已经浏览了网站上的其他解决方案,没有人减轻错误“线程中的exception”主“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 } } 

  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(); 

而不是books.remove(b)

使用

 listIterator.remove(); 

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

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

而不是books.remove(b)

试着用

  listIterator.remove(); 

迭代时,您无法从ArrayList删除项目。

你可以:

  • 使用ListIterator的remove()方法(每个next()最多一次)
  • 使用另一个List实现,比如CopyOnWriteArrayList ,保证永远不会抛出ConcurrentModificationException ,但这可能在您的情况下有点过分。

迭代列表时无法删除项目,应使用.remove()

同时删除此:

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

这不是必要的

 { 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“错误。有关错误的更多参考,请点击链接