Reputation: 333
im confused with a question which i was given, which is about bookshelf program. I have to create 2 classes called Book and BookShelf
I have more or less completed the Book class which contains these variables (id, author and title) with ( get, set , toString and constructors methods)
However for the BookShelf class, I am kind of clueless whether what i have done is correct
Here is what I am supposed to do at the BookShelf class
Create an addBook method, it takes in book object as input and adds the object into the bookshelf
returnBooks method, no parameter / arguments needed just return an arraylist of books in order
returnAuthorBooks, takes in author as input and returns an arraylist of books by the author
This is the code that i have done
import java.util.ArrayList;
import java.util.Collections;
public class BookShelf {
ArrayList<Book> listOfBooks = new ArrayList<Book>();
public void addBook(Book getTitle){
listOfBooks.add(getTitle);
}
public ArrayList<Book> returnBooks(){
ArrayList myBook = new ArrayList();
Collections.sort(myBook);
return myBook;
}
public ArrayList<Book> returnAuthor(Book author){
for (Book books : listOfBooks){
if (author.getAuthor() == books.getTitle()){
return listOfBooks;
}
}
return null;
}
}
Would like to clarify if there is any mistake here as for some reason i get the feeling that i have done something incorrect
Upvotes: 0
Views: 1455
Reputation: 393841
Your returnBooks
method returns an empty List. You should change
ArrayList myBook = new ArrayList();
to
ArrayList<Book> myBook = new ArrayList(listOfBooks);
In order to return a full sorted list.
Your returnAuthor
method has several problems :
==
instead of equals
(see this question).Upvotes: 1