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

查看:117
本文介绍了在Java中使用带标签的语句有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

'label':'statement'

'label' : 'statement'

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?

推荐答案

我所知道的唯一用途是您可以在 break continue 语句中使用标签。因此,如果您有嵌套循环,那么这是一次突破多个级别的方法:

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;
              }
          }
       }

如示例所示,它是如果你以嵌套的方式一次迭代两个东西(例如搜索匹配)并想继续 - 或者如果你正在进行正常的迭代,但是出于某种原因想要在嵌套中放置一个中断/继续,偶尔会有用用于循环。

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天全站免登陆