本文介绍了删除ArrayList对象问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我遇到了在处理赋值时从ArrayList中删除对象的问题如果我使用normalfor循环,它的工作方式如下I got an issue with deleting an object from ArrayList when working on the assignmentIf I use the "normal" for loop, it works as followingpublic void returnBook(String isbn){ for (int i = 0; i < booksBorrowed.size(); i++){ if (booksBorrowed.get(i).getISBN() == isbn){ booksBorrowed.get(i).returnBook(); booksBorrowed.remove(i); } }}然而,当我是尝试使用增强的for循环来简化代码,这不起作用并显示java.util.ConcurrentModificationException错误:However, when I'm trying to simplify the code with enhanced for-loop, that doesn't work and showing java.util.ConcurrentModificationException error:public void returnBook(String isbn){ for (Book book: booksBorrowed){ if (book.getISBN() == isbn){ book.returnBook(); booksBorrowed.remove(book); } }}希望你们能照亮我up .. Hope you guys could lighten me up..推荐答案避免ConcurrentModificationException的替代方案是:Your alternatives to avoid a ConcurrentModificationException are:List<Book> books = new ArrayList<Book>();books.add(new Book(new ISBN("0-201-63361-2")));books.add(new Book(new ISBN("0-201-63361-3")));books.add(new Book(new ISBN("0-201-63361-4")));收集您要在增强型for循环中删除的所有记录,并在完成迭代后,删除所有找到的记录。Collect all the records that you want to delete on enhanced for loop, and after you finish iterating, you remove all found records.ISBN isbn = new ISBN("0-201-63361-2");List<Book> found = new ArrayList<Book>();for(Book book : books){ if(book.getIsbn().equals(isbn)){ found.add(book); }}books.removeAll(found);或者您可以使用 ListIterator 在迭代过程中支持remove方法。Or you may use a ListIterator which has support for a remove method during the iteration itself.ListIterator<Book> iter = books.listIterator();while(iter.hasNext()){ if(iter.next().getIsbn().equals(isbn)){ iter.remove(); }}或者您可以使用第三方库,如 LambdaJ ,它会在幕后为您完成所有工作> Or you may use a third-party library like LambdaJ and it makes all the work for you behind the scenes>List<Book> filtered = select(books, having(on(Book.class).getIsbn(), is(new ISBN("0-201-63361-2")))); 这篇关于删除ArrayList对象问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-19 15:49