【问题标题】:Searching through books to get Author (Java)搜索书籍以获取作者 (Java)
【发布时间】:2017-09-21 18:30:52
【问题描述】:

我正在尝试查看我的书籍清单并归还该特定作者的所有书籍。我得到一个空列表。

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;
    }

主要看起来像这样。

Author author = new Author("James");
System.out.println(bookCollections.searchByAuthor(author));

【问题讨论】:

  • Author 的 equals 实现是什么样的?
  • Author 参数是否与 getMyAuthors() 中的参数相同,还是您创建了一个新对象?
  • 看起来等于没有实现。看到这个How to use contains
  • 我的作者没有平等的方法。也许这就是原因
  • 可能重复(无法更改我的近距离投票原因):ArrayList's custom Contains method。如需更多重复,请使用您最喜欢的搜索引擎并搜索java list contains custom object。您可以在 google 上添加 site:stackoverflow.com 以将结果限制在此站点。

标签: java loops search arraylist


【解决方案1】:

您的 Author 对象是一个值对象。您需要在 Author.java 类中同时实现 equalshashcode 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-22
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 2014-04-04
    • 2014-06-01
    • 2021-05-17
    • 1970-01-01
    相关资源
    最近更新 更多