簡體   English   中英

在for循環外返回for循環的元素

[英]Return an element of a for-loop outside the for-loop

如何返回for循環的元素?

private List<String> list = new ArrayList<String>();
//we only neeed one good element of the list
    String find(){
        for (int i=0; i<list.size(); i++){
            if (list.get(i).isGood()) {
                return list.get(i);
            }
        }
   return list.get(i); //doesn't work obviously, but how to make it work?
}

它沒有編譯,因為沒有return語句。 我想返回list.get(i)。

return調用之后不必調用break ,因為該方法在return語句之后退出。 因此, break語句將永遠無法執行,這就是為什么此代碼無法編譯的原因。

此外,如果循環后沒有返回值,則在循環后需要returnthrow語句,例如:

String find(){
   for (int i=0; i<list.size(); i++){
        if (list.get(i).isGood()) {
            return list.get(i);
        }
    }
    return null;
}

調用return不必break 它從調用return的行中退出該方法。 因此,您不必考慮打破循環。

了解有關退貨的更多信息。

當到達return指令時,代碼會立即從當前函數中退出 ,因此不接受任何后續行,因為它將永遠無法到達。

break; 調用是無法訪問的代碼語句。 任何代碼早午餐都應具有return語句。 使用Stream API:

String find() {
    return list.stream()
               .filter(Clazz::isGood)
               .findFirst()
               .get();
}

暫無
暫無

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

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