How do I break out of nested loops in Java?

前端 未结 30 2766
梦毁少年i
梦毁少年i 2020-11-21 11:51

I\'ve got a nested loop construct like this:

for (Type type : types) {
    for (Type t : types2) {
         if (some condition) {
             // Do somethin         


        
30条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 12:05

    Another one solution, mentioned without example (it actually works in prod code).

    try {
        for (Type type : types) {
            for (Type t : types2) {
                if (some condition #1) {
                    // Do something and break the loop.
                    throw new BreakLoopException();
                }
            }
        }
    }
    catch (BreakLoopException e) {
        // Do something on look breaking.
    }
    

    Of course BreakLoopException should be internal, private and accelerated with no-stack-trace:

    private static class BreakLoopException extends Exception {
        @Override
        public StackTraceElement[] getStackTrace() {
            return new StackTraceElement[0];
        }
    }
    

提交回复
热议问题