在Java中使用带标签的休息是一种很好的做法吗? [英] Is using a labeled break a good practice in Java?
问题描述
我正盯着2001年的一些旧代码并发现了这句话:
else {
do {
int c = XMLDocumentFragmentScannerImpl.this.scanContent();
if(c == 60){
XMLDocumentFragmentScannerImpl.this.fEntityScanner.scanChar();
XMLDocumentFragmentScannerImpl.this.setScannerState(1);
break label913;
}
我以前从未见过这个,并在此处发现标记符号:
http:// docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
这基本上不像 goto
?使用它是否是好的做法?这让我感到不安。
不,它不像goto,因为你不能去控制流的另一部分。 / p>
从您链接的页面:
break语句终止带标签的语句;它不会将控制流转移到标签上。控制流在标记(终止)语句之后立即转移到语句。
这意味着你只能打破当前正在循环的循环执行。
考虑这个例子:
first:
for(int i = 0; i< 10; i ++){
second:
for(int j = 0; j< 5; j ++)
{
打破xxx;
}
}
第三名:
for(int a = 0; a< 10; a ++){
}
您可以用 xxx
>第一个或第二个
(打破外部或内部循环),因为两个循环都在执行,当你点击 break
语句,但用第三
替换 xxx
将无法编译。
I'm staring at some old code from 2001 and came across this statement:
else {
do {
int c = XMLDocumentFragmentScannerImpl.this.scanContent();
if (c == 60) {
XMLDocumentFragmentScannerImpl.this.fEntityScanner.scanChar();
XMLDocumentFragmentScannerImpl.this.setScannerState(1);
break label913;
}
I had never seeen this before, and discovered labeled breaks here:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Doesn't this essentially function like goto
? Is it even good practice to use it? It makes me uneasy.
No, it's not like a goto, since you can't "go" to another part of the control flow.
From the page you linked:
The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is transferred to the statement immediately following the labeled (terminated) statement.
This means you can only break loops that are currently being executed.
Consider this example:
first:
for( int i = 0; i < 10; i++) {
second:
for(int j = 0; j < 5; j ++ )
{
break xxx;
}
}
third:
for( int a = 0; a < 10; a++) {
}
You could replace xxx
with first
or second
(to break the outer or inner loop), since both loops are being executed, when you hit the break
statement, but replacing xxx
with third
won't compile.
这篇关于在Java中使用带标签的休息是一种很好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!