Rind
Rind

Reputation: 333

java arraylist class program

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

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

Answers (1)

Eran
Eran

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 :

  1. It should take an author as input (I don't know if it should be a String or whether there is an Author class).
  2. You compare the book's authors with == instead of equals (see this question).
  3. You return the entire list of books if you find a book with the author you are looking for. You should only return the books of that author.

Upvotes: 1

Related Questions