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 } }
do not remove item list directly. use
remove()
method in iterator.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 calledhasnext
once. perhaps meant:while(listiterator.hasnext()){ book b = listiterator.next(); if (b.getbooktitle().equals(bookname)) { // ...
finally, can replace:
while(listiterator.hasprevious()) { listiterator.previous(); }
with
listiterator = books.listiterator();
Comments
Post a Comment