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 中使用标记语句有什么意义?
基础教程推荐
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01