[英]How should I change it to remove the last element from this list?
我正在嘗試從arraylist中刪除最后一個元素,但是這里的pop()方法無法按我的意願工作。 我應該如何更改代碼?
public String pop(){
String last;
if (stringList.size() == 0){
return null;
} else {
last = stringList.get(stringList.size()-1);
return last;
stringList.remove(stringList.size() - 1); //This is giving me error!
}
}
return stringList.remove(stringList.size() - 1);
其余的可以刪除,因為remove
返回被刪除的項目。
return
語句后面的代碼永遠無法執行。
Return語句應該最后出現,因為編譯器假定return語句之后沒有任何內容,並且可能會說不可達的語句
因為您正在執行return last;
stringList.remove(stringList.size() - 1);
之前的語句stringList.remove(stringList.size() - 1);
return語句之后的任何語句都不會執行。
修改后的代碼:
else {
last = stringList.get(stringList.size()-1);
stringList.remove(stringList.size() - 1); //Now it wont give any error!
return last;
}
return
語句之后的任何語句將不可訪問( unreachable code error )。 return
語句通常應該是您希望在method()中執行的最后一條語句。
使該語句冒泡,使錯誤超出return
,代碼應該可以正常工作。
stringList.remove(stringList.size() - 1); //goes above the return
return last;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.