简体   繁体   中英

Return an element of a for-loop outside the for-loop

How can I do to return an element of a for-loop?

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. I would like to return list.get(i).

Calling break after a return call is unnecessary, since the method is exited after the return statement. Therefore the break statement has no chance of ever being executed which is why this code doesn't compile.

Furthermore you need a return or throw statement after the loop in case no value is returned form the loop, eg:

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 . It exits the method from the line where return is called. 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. With Stream API:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM