Reputation: 347
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).
Upvotes: 0
Views: 894
Reputation: 3453
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();
}
Upvotes: 0
Reputation: 26926
When a return
instruction is reached the code exit immediately from the current function, so any following line is not accepted because will never be reached.
Upvotes: 0
Reputation: 82461
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, e.g.:
String find(){
for (int i=0; i<list.size(); i++){
if (list.get(i).isGood()) {
return list.get(i);
}
}
return null;
}
Upvotes: 3