Iteration loop inside another loop

微笑、不失礼 提交于 2019-12-24 15:42:20

问题


Is there any way I can use an Iterator inside another loop? I am asking this because I can't find a way to bring the iterator at the start of the list again after the first loop is done and therefore at a second loop the iter.hasNext() will give me false

Iterator iter = list.iterator();
for (int i=0;i<30;i++)
{
 while (iter.hasNext())
 {
  ...
 }

}

回答1:


Iterator iter;
for (int i=0;i<30;i++)
{
    iter = list.iterator();
    while (iter.hasNext())
     {
      ...
     }

}



回答2:


You could just reset the iterator in the outer loop:

for (int i=0;i<30;i++) {
    Iterator iter = list.iterator();
    while (iter.hasNext()) {
        Object obj = iter.next();
    }
}



回答3:


The iterator was consumed during first cycle of a loop (i==0). To fix the problem u need to reinitialise the item reference inside a loop. Best!



来源:https://stackoverflow.com/questions/29956245/iteration-loop-inside-another-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!