I will give you some hints.
First, I would use Set
instead of an array as you are using.
Then, here:
if (booksArray[i] == book){
This might not work, depending on how you have implemented it. In there you are comparing the reference in booksArray[i]
with the reference of book
. How do you know when a book is equal another? For example, is it by a field name
inside, so when two instances of book have the same name are considered equal?
So, unless you have a requirement for arrays, I would recommend yoy use a Set
, implement the equals and hash methods inside the class Book and make the comparison with contains().
EDIT
If you are not allowed to use Set
as per your comment, then understand your problem first.
If you do
book book = new Book();
You have created a reference. Then if you put this very same object in the array, you get the same reference inside the array, so when you compare them with ==
, they will point to the same object reference and the result will be true
.
However, if you obtain the books from somewhere else, or copy the object inside the array (which will create a new Book object, and therefore, with a different reference) then both references will always be different.
In this case, you don't want to compare objects by their reference, but by something else. In that case, (1) you need to implement (override) both equals()
and HashCode()
methods inside Book. In these methods you specify what makes books equal. For example, books can be equal if they have the same "name" (e.g. book1.name is equal book2.name). Or if they have the same name AND the same author... This depends on your object, it is your decision. And finally (2) you compare books with equals()
and not with ==
. Here you have an example.
By the way, this is an aside note... To improve your code I would recommend you to do:
int addBookToLibrary(Book book) throws CapacityReachedException {
if( isLibraryMaxCapacity() ) {
throw new CapacityReachedException("The library is full");
}
if (!contains(book)) {
addBook(book);
}
return numberOfBooks();
}
And then you implement separately the methods isLibraryMaxCapacity()
, contains(book)
, addBook(book)
and numberOfBooks()
. They are all very simple.