我正在尝试使用列表迭代器从列表中删除对象。我已经浏览了网站上的其他解决方案,但没有一个解决方案可以缓解错误“线程“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()
迭代器中的方法。
-
您的代码也存在缺陷,因为它假设还有其他列表项:
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)) {
// ...
-
最后,您可以替换:
while(listIterator.hasPrevious()) {
listIterator.previous();
}
with
listIterator = books.listIterator();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)