尝试使用列表迭代器删除对象 [英] Trying to remove an object with list iterator
本文介绍了尝试使用列表迭代器删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用列表迭代器从列表中删除对象.我浏览了网站上的其他解决方案,但都没有缓解错误线程"main"中的异常" java.util.ConcurrentModificationException"
I'm trying to remove an object from a list using the list iterator. I've gone through the other solutions on the website and none have alleviated the error "Exception in thread "main" 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
}
}
推荐答案
-
请勿直接从列表中删除项目.在迭代器中使用
remove()
方法.
您的代码也有缺陷,因为它假设还有其他列表项:
Your code is also flawed in that it assumes there are additional list items:
while(listIterator.hasNext()){
Book b = listIterator.next();
if (listIterator.next().getBookTitle().equals(bookName)) {
// eek
在这里您两次呼叫next()
,但是您只呼叫了一次hasNext
.也许你是说:
Here you call next()
twice, yet you've only called hasNext
once. Perhaps you meant:
while(listIterator.hasNext()){
Book b = listIterator.next();
if (b.getBookTitle().equals(bookName)) {
// ...
最后,您可以替换:
Finally, you can replace:
while(listIterator.hasPrevious()) {
listIterator.previous();
}
使用
listIterator = books.listIterator();
这篇关于尝试使用列表迭代器删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文