0
要求:從不同對象的列表中找到最後一棒的對象,拋出NoSuchElementException異常,如果沒有找到從對象列表,拋出異常查找最後一個對象,如果沒有找到
Bar findLast(List stuff) throws NoSuchElementException { }
我的解決辦法:
Bar findLast(List stuff) throws NoSuchElementException {
Bar bar = new Bar();
for(int i=stuff.size()-1;i>=0;i--){
if(stuff.get(i).getClass().isInstance(bar)){
return (Bar) stuff.get(i);
}
}
throw new NoSuchElementException();
}
問題:
- 我們是否需要在方法頭的
throws NoSuchElementException
? - 我們是否需要
try catch
塊在方法內的最後一行?如果是這樣,怎麼樣? - 此代碼是可用的嗎?