? 03. Solution
01. Scene display
As shown in the figure above, we want to end the for loop and use return.
The implementation results are as follows:
We can see that only Zhao Liu has not been printed, and the subsequent array elements are still executed.
In other words, the keyword "return" is executed here as the keyword "continue" in a normal for loop.
02. Cause analysis
We know that in an ordinary for loop, the body that wants to end (terminate) the cycle early uses "break".
End the current cycle and proceed to the next cycle using "continue"
In addition, in a normal for, using "return" will not only force the end of the for loop body, but also prematurely end the entire method that contains the loop body.
In forEach () in Java8, "break" or "continue" is not allowed, and the meaning of return is no longer what the original return stands for.
Let's look at the source code:
ForEach (), after all, is a method, not a loop body, what does it use to end the execution of a method? Return, of course.
Java is not everything. Stop complaining about its rubbish.
Option 1: use the original foreach loop
Brothers who have used eclipse should know that when we type: foreach, and then press the shortcut key: Alt+/, there will be a code prompt for foreach.
As shown in the figure above, the for loop in this format is the real foreach loop.
If you enter it in idea, there will be no code hints if you follow the above operation, so how can it be called up in idea?
The for loop can be terminated prematurely.
Method 1: break
Method 2: return (not recommended)
Scenario 2: throw an exception
We know that to end the execution of a method, the normal logic is: use return
However, in the actual operation, there are often many non-unexpected circumstances that lead to early termination of the code, such as null pointer exception. In fact, we can also achieve the purpose of terminating the forEach () method by throwing a false exception.
If you think this way is unfriendly, you can pack it again.
This way, it's perfect.
One thing to note here is to make sure that there are no exceptions that other code might throw in your forEach () method that you manually throw and catch.
Otherwise, when the code should really be terminated because of the exception, because we captured it manually and didn't do anything about it, wouldn't it be to shoot ourselves in the foot?