在arraylist中搜索实例变量

时间:2016-02-17 07:03:07

标签: java

我试图创建一个方法来返回来自不同类的对象。

例如:

public Book searchTitle(String title) {
    for (Book book : library) {
        if (book.getTitle().equals(title)) {
            return book;
        }
    }

// If the book is not found, I have no return and the program won't compile.
//How do I make the method work in the case that the book is not found? 

1 个答案:

答案 0 :(得分:4)

如果找不到null,则返回Book或抛出异常:

public Book searchTitle(String title) {
    for (Book book : library) {
        if (book.getTitle().equals(title)) {
            return book;
        }
    }
    return null;
}