打破循环或增加计数器的更快方法?

有没有更快的方法来增加计数器或从外循环中断?


while(myArrayList.get(i) > myNumber) {

    // some operations


    if(i + 1 < myArrayList.size())

        i++;

    else

        break;

}


GCT1015
浏览 209回答 3
3回答

慕森卡

编写代码的更好方法肯定存在:for (int i = 0; i < myArrayList.size(); i++) {&nbsp; &nbsp; if (myArrayList.get(i) <= myNumber) break;&nbsp; &nbsp; //Some operations...}

繁花如伊

您需要先检查大小以避免超出列表末尾并出现错误。int i;for (i = 0; i < myArrayList.size(); i++)&nbsp;&nbsp; &nbsp; if (myArrayList.get(i) <= myNumber)&nbsp; &nbsp; &nbsp; &nbsp; break;使用 Streams API,您可以做到int n = IntStream.range(0, myArrayList.size())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.filter(i -> myArrayList.get(i) <= myNumber)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.findFirst()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.orElse(myArrayList.size()); // or -1

弑天下

for 循环在这里更合适:int counter = 0for(int i = 0; i < myArrayList.size(); i++) {&nbsp; &nbsp; if(!(myArrayList.get(i) > myNumber)) {&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }&nbsp; &nbsp; counter++;}如果意图是大于 的计数值myNumber,则break可能会排除某些值(除非您知道它myArrayList已排序),并且循环应该是:for(int i = 0; i < myArrayList.size(); i++) {&nbsp; &nbsp; if(myArrayList.get(i) > myNumber) {&nbsp; &nbsp; &nbsp; &nbsp; counter++;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java