简体   繁体   English

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

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

How can I do to return an element of a 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?
}

It doesn't compile because there is no return statement. 它没有编译,因为没有return语句。 I would like to return list.get(i). 我想返回list.get(i)。

Calling break after a return call is unnecessary, since the method is exited after the return statement. return调用之后不必调用break ,因为该方法在return语句之后退出。 Therefore the break statement has no chance of ever being executed which is why this code doesn't compile. 因此, break语句将永远无法执行,这就是为什么此代码无法编译的原因。

Furthermore you need a return or throw statement after the loop in case no value is returned form the loop, eg: 此外,如果循环后没有返回值,则在循环后需要returnthrow语句,例如:

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

You don't have to break as you have called return . 调用return不必break It exits the method from the line where return is called. 它从调用return的行中退出该方法。 So you don't have to think to break the loop. 因此,您不必考虑打破循环。

Learn more about return . 了解有关退货的更多信息。

当到达return指令时,代码会立即从当前函数中退出 ,因此不接受任何后续行,因为它将永远无法到达。

break; call is unreachable code statement. 调用是无法访问的代码语句。 Any code brunch should have return statement. 任何代码早午餐都应具有return语句。 With Stream API: 使用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