-1

Im trying to look through my list of books and return all the books by that particular author. Im getting back an empty list.

public ArrayList<Book> searchByAuthor(Author author) {
    ArrayList<Book> bookList = new ArrayList<>();
    for (int i = 0; i < myBooks.size(); i++) {
        if (myBooks.get(i).getMyAuthors().contains(author)) {
            bookList.add(myBooks.get(i));      
        }
    }
    return bookList;
}



public ArrayList<Author> getMyAuthors() {
        return myAuthors;
    }

The main looks somethings like this.

Author author = new Author("James");
System.out.println(bookCollections.searchByAuthor(author));
xxFlashxx
  • 261
  • 2
  • 13
  • 2
    What does the equals implementation of `Author` look like? – azurefrog Sep 21 '17 at 18:31
  • Is Author parameter same as in getMyAuthors() or did you create a new object? – Vladimír Bielený Sep 21 '17 at 18:34
  • 1
    Looks like equals is not implemented. See this [How to use contains](https://stackoverflow.com/questions/46332059/how-to-use-contains-on-custom-type-arraylist-in-java/46332573#46332573) – JavaProgrammer12 Sep 21 '17 at 18:37
  • I don't have an equal method in my Author.. maybe thats why – xxFlashxx Sep 21 '17 at 18:41
  • Possible duplicate (can't change my close-vote reason): [ArrayList's custom Contains method](https://stackoverflow.com/q/8322129). For more duplicates use your favorite searching engine and search for `java list contains custom object`. You can add `site:stackoverflow.com` at google to limit results to this site. – Pshemo Sep 21 '17 at 18:46

1 Answers1

0

Your Author object is a value object. you need to implement both equals and hashcode methods in your Author.java class.

Yohannes Gebremariam
  • 2,225
  • 3
  • 17
  • 23