mercredi 11 novembre 2020

Method to add unique object instance into an ArrayList is not working

First of all: I am new to Java and this site, this is my first post here. I have searched on both Google and this site regarding my question and found some (a lot) of similar posts, but I can't found one that helps me with my coding problem.

I have two classes: Library and Book. For the last four hours, I have been trying to write a method that adds a book to the Library (to an ArrayList) if it's unique. If it's not unique, a message will be printed saying that the Library already has the book.

Class: Library

Field:

private ArrayList<Book> bookList;

Constructor:

bookList = new ArrayList<Book>();

Method:

public void addBook(Book bookTitle)
{
for(Book bookId:bookList) {
if (bookTitle.equals(bookId)) {
bookList.add(bookTitle);
System.out.println("Book registered."); }
else { System.out.println("This book is not unique"; }                
} 

}

I do not get any compilation error but it's not working. The object is not added to my ArrayList, no message is printed. I have also tried with:

if (bookId != bookTitle)

without result.

Hope someone here can help and explain to me what I am doing wrong, it would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire