我有以下循环,我只想运行一次。我怎样才能做到这一点?
for (AnnotationData annotations : annotation)
运行一次的循环并不是一个循环。
如果annotations
是一个数组,则使用annotations[0]
. 如果是List
,请执行annotations.get(0)
。否则,做annotations.iterator().next()
. 如果您不确定该集合是否至少包含一个元素,请务必先检查该元素。
这会更清楚,因为当人们看到 afor
他们通常期望一个循环。一个实际上,嗯,循环。
刚刚爆发!
for (AnnotationData annotation : annotations) {
// do something with "annotation"
break; // only execute loop body once
}
其他答案是使用计数器或标志!?有些人为了做最简单的事情而编写了多少代码,这让我永远感到惊讶。通常,程序员越差,他们写的代码就越多。
一些评论者误解了非循环版本会使用“更少的代码”或“更少的行”。这样的说法是不真实的......这是精确的非循环等效代码:
if (!annotations.isEmpty()) {
AnnotationData annotation = annotations.get(0);
// do something with "annotation"
}
这使用了相同的行数,但需要多 23个字符的代码,尽管我承认它的意图更加明确。
不需要任何计数器。只需break
在最后添加一个:
for (AnnotationData annotations : annotation){
//your all code
break;
}
int i=0;
for (AnnotationData annotations : annotation){
if(i==1)
{
break;
}
i++;
}