Java Continue 标签已弃用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6650239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 12:22:44  来源:igfitidea点击:

Java Continue Label is Deprecated?

javadeprecatedcontinue

提问by Cosmin Cosmin

I have 2 fors, after the nested for I have some code which I don't want to execute if a condition is true inside the nested for. If I use break that code would execute, so (as I learned in SCJP) I used continue label;for the outer for. Is this a deprecated usage of Java ? Old fashioned ? Somebody suggested to use recursion or something else, but for me this is perfectly normal, simple, up-to-date and the perfect way of doing it.

我有 2 个 fors,在嵌套 for 之后我有一些代码,如果嵌套 for 中的条件为真,我不想执行这些代码。如果我使用 break 代码将执行,所以(正如我在 SCJP 中学到的)我用于continue label;外部 for。这是 Java 的弃用用法吗?老式的?有人建议使用递归或其他方法,但对我来说,这是完全正常、简单、最新且完美的方法。

here:
for (bla bla) {
   for (bla bla) {
      if (whatever) continue here;
   }
// some code I don't want to execute if whatever is true
}

Thanks

谢谢

Edited:
If I rephrase my question as: How can you 'navigate' between multiple nested fors ? This approach would be the 'recommended' way ? because this is what it says in SCJP Book. If not .. would this mean that Katherine Sierraand Bert Batesare wrong ?

编辑:
如果我将我的问题改写为:如何在多个嵌套的 fors 之间“导航”?这种方法将是“推荐”的方式?因为这是 SCJP Book 中所说的。如果不是..会这是不是意味着Katherine SierraBert Bates有错吗?

Edited2:
Why is continue label;discouraged ? I want an answer of the concepts or inside workings of OOP or Java, what might go wrong ..

Edited2:
为什么continue label;不鼓励?我想要一个关于 OOP 或 Java 的概念或内部工作的答案,可能会出什么问题..

采纳答案by Mark Pope

The answer is: it depends. If you find yourself using continuea lot then it might be a sign that your code needs a refactor. However, in the scenario you've given it seems like an OK place to use it.

答案是:视情况而定。如果您发现自己使用continue了很多,那么这可能表明您的代码需要重构。但是,在您给出的场景中,它似乎是一个可以使用它的地方。

回答by Peter Lawrey

I would say its discouraged. It still has valid uses where alternatives are more complex or error prone (i.e. not an improvement)

我会说它气馁。在替代方案更复杂或更容易出错(即不是改进)的情况下,它仍然具有有效的用途

回答by Mikael Vandmo

I would refactor to make it more readable.

我会重构以使其更具可读性。

Example:

例子:

if (!checkWhatever()) {
    // some code I don't want to execute if whatever is true
}
boolean checkWhatever() {
    for (bla bla) {
       for (bla bla) {
          if (whatever) return false;
       }
    }
    return true;
}

回答by ahcox

With reference to your Edit 2, it is always going to look a bit iffy because it violates an older programming orthodoxy than OO: 'structured programming' (see http://en.wikipedia.org/wiki/Structured_programming). It smacks of goto as well, and all good programmers know they need to go to confession if they let a goto into their code.

参考您的 Edit 2,它总是看起来有点不确定,因为它违反了比 OO 更旧的编程正统:“结构化编程”(参见http://en.wikipedia.org/wiki/Structured_programming)。它也有 goto 的味道,所有优秀的程序员都知道,如果他们让 goto 进入他们的代码,他们需要忏悔。

There could be some concern that it might make it harder for a compiler to analyse the control flow of a function, but it is the sort of tool that typically gets used for efficiency reasons. For instance, the Apache implementation of java.lang.Stringuses it in this function that is at least intended to be an optimisation:

可能有人担心它可能会使编译器更难分析函数的控制流,但通常出于效率原因使用这种工具。例如,Apache 实现java.lang.String在这个函数中使用它,至少是为了优化:

/*
 * An implementation of a String.indexOf that is supposed to perform
 * substantially better than the default algorithm if the "needle" (the
 * subString being searched for) is a constant string.
 *
 * For example, a JIT, upon encountering a call to String.indexOf(String),
 * where the needle is a constant string, may compute the values cache, md2
 * and lastChar, and change the call to the following method.
 */
@SuppressWarnings("unused")
private static int indexOf(String haystackString, String needleString,
        int cache, int md2, char lastChar) {
    char[] haystack = haystackString.value;
    int haystackOffset = haystackString.offset;
    int haystackLength = haystackString.count;
    char[] needle = needleString.value;
    int needleOffset = needleString.offset;
    int needleLength = needleString.count;
    int needleLengthMinus1 = needleLength - 1;
    int haystackEnd = haystackOffset + haystackLength;
    outer_loop: for (int i = haystackOffset + needleLengthMinus1; i < haystackEnd;) {
        if (lastChar == haystack[i]) {
            for (int j = 0; j < needleLengthMinus1; ++j) {
                if (needle[j + needleOffset] != haystack[i + j
                        - needleLengthMinus1]) {
                    int skip = 1;
                    if ((cache & (1 << haystack[i])) == 0) {
                        skip += j;
                    }
                    i += Math.max(md2, skip);
                    continue outer_loop;
                }
            }
            return i - needleLengthMinus1 - haystackOffset;
        }

        if ((cache & (1 << haystack[i])) == 0) {
            i += needleLengthMinus1;
        }
        i++;
    }
    return -1;
}

回答by ToolmakerSteve

Refactor to make it more readable, by placing the inner loop in its own method:

通过将内部循环置于其自己的方法中,重构以使其更具可读性:

for (bla bla) {   
  DoStuff();
}
void DoStuff() {
  for (bla bla) {
    if (whatever) return;
  }
  // some code to execute when whatever is false.
}

The principle: If a method becomes complex enough to require LABELING a block, consider refactoring part of that method into a separate method, such that no label is needed.

原则:如果一个方法变得足够复杂,需要对一个块进行标签,考虑将该方法的一部分重构为一个单独的方法,这样就不需要标签了。

Similarly, it is unwise to make methods that are THREE loops deep. Unless the loops are very simple. Even if no labels are needed. Make sure the outermost flow construct (a loop, or an if/else, or a switch) is easy to read, by hiding complexity inside other methods. Even if those methods are only called from one place.

同样,创建深度为三个循环的方法也是不明智的。除非循环非常简单。即使不需要标签。通过将复杂性隐藏在其他方法中,确保最外层的流结构(循环、if/else 或开关)易于阅读。即使这些方法只从一处调用。

回答by Evvo

Use a boolean called 'success' or something like that. It's much easier to read and to follow the flow. Gotos should only be used for error handling.

使用名为“成功”或类似的布尔值。阅读和遵循流程要容易得多。Goto 应该只用于错误处理。

boolean success = true;
for(int outer = 0; (outer <= outerLimit) && sucess; outer++)
{
    for(int inner = 0; (inner <= innerLimit) && success; inner++)
    {
        if( !doInnerStuff() )
        {
            success = false;
        }
    }

    if( success )
    {
        success = doOuterStuff();
    }
}