我正忙着为我的认证学习,我偶然发现了一个我以前从未听过的概念 - "标签声明".例如:
'label':'声明'
L1: while(i < 0){
L2: System.out.println(i);
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是..为什么?这有什么用,什么时候想用这样的东西?
And*_*yle 25
我所知道的唯一用途是你可以使用标签break或continue语句.因此,如果您有嵌套循环,那么这是一次突破多个级别的方法:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如示例所示,如果您以嵌套方式一次迭代两个事物(例如搜索匹配项)并希望继续 - 或者如果您正在进行正常迭代,但是出于某种原因想要放置一个在嵌套for循环中中断/继续.
不过,我倾向于每隔几年才使用一次.有一个鸡蛋和鸡蛋,因为它们是一个很少使用的构造,所以很难理解,所以如果代码可以用另一种方式清楚地写,我将避免使用标签.
Pet*_*rey 21
它可用于避免需要"未找到"标志.
FOUND: {
for(Type t: list)
if (t.isTrue())
break FOUND;
// handle not found.
}
Run Code Online (Sandbox Code Playgroud)
这可能是滥用标签,但你可以使用它们在没有循环的情况下破坏.
LABEL: {
if(condition)
break LABEL;
// do something
}
Run Code Online (Sandbox Code Playgroud)
它也可以用来混淆人,这是避免它的一个很好的理由.;)
http://www.google.com
while(true) break http;
Run Code Online (Sandbox Code Playgroud)