[英]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: 此外,如果循环后没有返回值,则在循环后需要
return
或throw
语句,例如:
String find(){
for (int i=0; i<list.size(); i++){
if (list.get(i).isGood()) {
return list.get(i);
}
}
return null;
}
当到达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.