在 Java 中使用标记语句有什么意义?

2022-01-25 00:00:00 label java

我正忙于学习我的认证,我偶然发现了一个我以前从未听说过的概念 - 标签声明".例如:

I'm busy studying for my certification and I stumbled upon a concept I've never even heard before - "Labeled Statements". e.g:

标签":声明"

L1: while(i < 0){
     L2: System.out.println(i);
}

所以我的问题是.. 为什么?这有什么用?什么时候需要使用这样的东西?

So my question is.. why? How is this useful and when would one want to use something like this?

推荐答案

我知道的唯一用途是您可以在 breakcontinue 中使用标签陈述.因此,如果您有嵌套循环,这是一种一次突破多个级别的方法:

The only use that I'm aware of is that you can use labels in break or continue statements. So if you have nested loops, it's a way to break out of more than one level at a time:

OUTER: for (x : xList) {
          for (y : yList) {
              // Do something, then:
              if (x > y) {
                  // This goes to the next iteration of x, whereas a standard
                  // "continue" would go to the next iteration of y
                  continue OUTER;
              }
          }
       }

正如示例所暗示的,如果您以嵌套方式一次迭代两个事物(例如搜索匹配项)并想要继续,或者如果您正在进行正常迭代,但出于某种原因想要在嵌套的 for 循环中放置中断/继续.

As the example implies, it's occasionally useful if you're iterating over two things at once in a nested fashion (e.g. searching for matches) and want to continue - or if you're doing normal iteration, but for some reason want to put a break/continue in a nested for loop.

不过,我倾向于每隔几年才使用一次.有一个先有鸡还是先有蛋的问题,因为它们是一种很少使用的构造,所以很难理解,所以如果代码可以用另一种方式清楚地编写,我将避免使用标签.

I tend to only use them once every few years, though. There's a chicken-and-egg in that they can be hard to understand because they're a rarely-used construct, so I'll avoid using labels if the code can be clearly written in another way.

相关文章