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

时间:2013-04-18 13:27:12

标签: java listiterator

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

    }
    }

6 个答案:

答案 0 :(得分: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();
    

答案 1 :(得分:5)

而不是books.remove(b)

使用

listIterator.remove();

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

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

答案 2 :(得分:0)

而不是books.remove(b)

尝试使用

   listIterator.remove();

答案 3 :(得分:0)

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

你可以:

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

答案 4 :(得分:0)

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

同时删除此内容:

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

这不是必要的

答案 5 :(得分: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“错误。有关错误的更多参考,请关注link

相关问题