I agree with everything said by @VoidOfUnreason and @RetailCoder, and won't bother repeating them. I'll just note that there are many careless bugs.
In Library.add()
, your if-condition is wrong. Also, the problem specifies that it should return a boolean indicating whether the operation succeeded. That's open to interpretation: what constitutes a failure? Running out of memory? Not likely; the customary action in that case would be to helplessly let the OutOfMemoryException
propagate. What if you try to add the same book to the library twice? That's a reasonable failure mode. What if you add a second copy of a book that is already in the library? That should succeed, I would think.
In Library.findTitles()
, your for-loop is wrong. A common idiom in languages with zero-based arrays is…
for (int i = 0; i < n; i++) { ... }
In any case, modern Java code would typically say instead…
for (Book b : allBook) { ... }
The specification says that .findTitles()
should return a list of matching books — so where's your new list?
A hint for Library.toString()
: you want to build a long string, so use a StringBuilder
object. For each book in the library, you'll want to appends its string representation to the result.
In the Book()
constructor, your validation probably doesn't behave the way you intended.
In Book.toString()
, just slapping bookTitle
and bookAuthor
together is unlikely to yield a satisfactory result.
Since you overrode Book.equals()
, you should also implement Book.hashCode()
to be consistent. Otherwise, you would not be able to store Book
s in a HashMap
or Hashtable
.
I would rename your instance variables allBook
and bookAuthor
using their plurals. The code will read more smoothly, and logic mistakes will be less likely.
You really ought to have some test cases. Usually, that would be accomplished using JUnit
, but for a beginner, making a public static void main(String[] args)
would work fine. Implementing the tests would be a good exercise for you, and would help to uncover many bugs.