I am working with an ArrayList that contains multiple objects. I would like to remove a specific object from the list. However, I do not know the index of this object; instead, I only know the value of one of its properties (for example, its ID or name). What is the correct or recommended way to remove such an object from the ArrayList in Java?
I tried to iterate over the ArrayList and remove the book when its ISBN matches the target, like this:
while (searchBook) {
System.out.print("Enter the ISBN (10 or 13 digits) of the book to remove: ");
bookISBN = scan.nextLine().trim();
if (bookISBN.length() != 10 && bookISBN.length() != 13) {
System.out.println("[!] Invalid ISBN. It must contain exactly 10 or 13 digits.");
}
Book suchBook = new Book(null, null, bookISBN);
for (Book book : books) {
if (suchBook.getIsbn(suchBook).equals(bookISBN)) {
books.remove(new Book(null, null, bookISBN));
searchBook = false;
}
}
System.out.println("[!] No book found with the given ISBN.");
}