java - Trying to remove an object with list iterator -


i'm trying remove object list using list iterator. i've gone through other solutions on website , none have alleviated error "exception in thread "main" java.util.concurrentmodificationexception"

here code not executing :

void patronreturn(string bookname) { //       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 next iterator can remove previous ?         //books.remove(listiterator.next());; // todo see if correct      }     } 

  1. do not remove item list directly. use remove() method in iterator.

  2. your code flawed in assumes there additional list items:

    while(listiterator.hasnext()){     book b = listiterator.next();     if (listiterator.next().getbooktitle().equals(bookname)) {        // eek 

    here call next() twice, yet you've called hasnext once. perhaps meant:

    while(listiterator.hasnext()){     book b = listiterator.next();     if (b.getbooktitle().equals(bookname)) {        // ... 
  3. finally, can replace:

    while(listiterator.hasprevious()) {     listiterator.previous(); } 

    with

    listiterator = books.listiterator(); 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -