[英]Run for-each loop just one time
我有以下循環,我想只運行一次。 我怎樣才能做到這一點?
for (AnnotationData annotations : annotation)
運行一次的循環不是一個循環。
如果annotations
是一個數組,請使用annotations[0]
獲取第一個annotations[0]
。 如果是List
,請執行annotations.get(0)
。 否則,請執行annotations.iterator().next()
。 如果您不確定該集合是否至少包含一個元素,請務必先檢查該元素。
這將是更清楚,因為當人們看到了一個for
他們通常想到的循環。 一個實際上,好吧,循環。
剛爆發!
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++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.