![](/img/trans.png)
[英]Java: How to search an arraylist for a instance variable of an object in the array
[英]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.