在 Java 中使用标记语句有什么意义? [英] What's the point of using labeled statements in Java?

查看:143
本文介绍了在 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.

这篇关于在 Java 中使用标记语句有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆