Let's look at what you were trying.
- You added 2 objects to an
ArrayList
- You then tried to remove one of the objects from the
ArrayList
by calling remove(String s)
.
First, there is no remove(String s)
. What your code is actually calling is remove(Object o)
. Even though a String
is an Object
, the Object
this method really expects is your Library
object, which is why you have answers that suggest that you have to override the equals()
and hashCode()
Another approach would be to extend the ArrayList class with your own custom class (Library
), that has Book
objects, and implement a remove(String s)
.
As far as the "Titles: " only appearing once in your results, an @Override toString() is in order for that.
Library
custom class that extends ArrayList
:
public static class Library extends ArrayList<Book> {
// Adding an overload remove method that accepts a String
public void remove(String book) {
// Find the book to remove
for (int i = 0; i < size(); i++) {
if (get(i).getTitle().equals(book)) {
// This remove() is one of the default remove methods
// that is part of an ArrayList
remove(i);
break;
}
}
}
// This will display "Titles: " once along with every
// book in the ArrayList
@Override
public String toString() {
StringBuilder sb = new StringBuilder("Titles: ");
// Append each book to the returning String
forEach(book -> sb.append(book).append("\n"));
return sb.toString();
}
}
Book
custom class:
public static class Book {
private String title;
public Book(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
@Override
public String toString() {
// You could append additional information like
// author, publisher, etc...
return title;
}
}
Usage:
public static void main(String[] args) throws Exception {
Library books = new Library();
books.add(new Book("The Gunslinger"));
books.add(new Book("The Drawing of the Three"));
System.out.println("After add: ");
System.out.println(books);
books.remove("The Gunslinger");
System.out.println("After remove: ");
System.out.println(books);
}
Results:
After add:
Title: The Gunslinger
The Drawing of the Three
After remove:
Title: The Drawing of the Three