我有一个书单
List<Book> books = new ArrayList<Book>();
public class Book {
String name;
List<Author> authors;
}
图书包含作者列表,其中包含 ID、姓名和年龄
public class Author {
int ID;
String Name;
int Age;
}
我可以遍历书籍列表并在 Name = x 处返回 Book
,但我不确定如何搜索 Author
并在 Name = y 处返回。
最佳答案
添加一个方法hasAuthor(String)
给你的Book
循环遍历 List<Author>
列出并比较名称。像这样:
boolean hasAuthor(String name) {
for (Author author : authors) {
if (author.name.equals(name)) {
return true;
}
}
return false;
}
要查找具有特定作者的书籍,您可以遍历 List<Book>
并调用 hasAuthor(String)
方法。
关于Java变量对象搜索列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18301387/