What#39;s the point of using labeled statements in Java?(在 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?
推荐答案
我知道的唯一用途是您可以在 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;
}
}
}
正如示例所暗示的,如果您以嵌套方式一次迭代两个事物(例如搜索匹配项)并想要继续,或者如果您正在进行正常迭代,但出于某种原因想要在嵌套的 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 中使用标记语句有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 中使用标记语句有什么意义?


- 获取数字的最后一位 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 转换 ldap 日期 2022-01-01