我有一个项目,其中有一个“for 循环”迭代数组列表。我需要在中间停止迭代并再次继续。我尝试通过在两者之间应用“if else”条件来做到这一点,但它不起作用。
我有一个大小为 2500 的数组列表,我需要 for 循环迭代 500 次,然后等待并调用函数,然后再次继续循环并在下一个 500 次之后停止,依此类推。
这是我迄今为止尝试过的:
int msgCount = 0;
ArrayList<JSONInput > saveArrayList = new ArrayList<JSONInput >();
for(JSONInput jsonInput: arrXMLString){
publisher.send(jsonInput);
saveArrayList.add(jsonInput);
if(msgCount<500){ // it will loop for 500 times and increment msgCount
msgCount++;
} else {
msgCount=0;
SentService.sendArraylist(saveArrayList);
saveArrayList.clear();
}
}
这不起作用。循环不会停止,当我调试时,它会在“else”条件下停止,但循环不会等待条件完成。
最佳答案
I have arraylist of size 2500 and i need for loop to iterate 500 times and then wait and call a function and again continue looping and stop after 500 and so on
创建一个临时列表以将每个项目添加到其中。使用 for 循环并检查循环的索引值 - 如果该值可被 500 整除,则调用必要的代码。
//presuming arrXMLString is a List
List<JSONInput> saveArrayList = new ArrayList<JSONInput>();
for ( int i = 0; i < arrXMLString.size(); i++ ){
JSONInput jsonInput = arrXMLString.get(i);
publisher.send(jsonInput);
saveArrayList .add(jsonInput);
if ( i % 500 == 0 && i > 0 ){
SentService.sendArraylist(tempList);
saveArrayList .clear();
}
}
关于java - Java 中 For 循环的停止和继续循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29949405/