簡體   English   中英

在arraylist中搜索實例變量

[英]Search arraylist for an instance variable

我正在嘗試創建一種方法,該方法將從另一個類返回一個對象。

例如:

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? 

如果找不到Book則返回null或引發異常:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM