【问题标题】:Is there a way to go back by one iteration in a for-each loop?有没有办法在 for-each 循环中通过一次迭代返回?
【发布时间】:2021-05-20 16:30:57
【问题描述】:

例如,如果我要...

for (String s : arraylist) {
    // Do something with string
}

如果不可能,是否有另一种方法可以在控制迭代计数器的同时遍历某种集合类?我尝试查看this question 的答案,但想不出一种对我来说很清楚的方法。

欢迎提出任何建议!

【问题讨论】:

  • 不,for-each 循环不可能。您需要创建索引 for 循环或 while 循环。
  • A ListIterator 确实具有“以前的”功能。既然它出现(通过命名)arrayList 是一个List,那么考虑使用arrayList.listIterator()

标签: java loops foreach


【解决方案1】:

这取决于您要执行的操作,但您可以使用 while-loop 并在适当时增加索引:

while(i<limit){
   list.get(i);
   // Do something

   if(someConditionMet){
     i++
   }
}

或者您可以使用for-loop,而无需在每次迭代后增加索引:

for (int i = 0; i < 5; ) {
   list.get(i);
   // Do something

    if(someConditionMet){
        i++;
    }
}

此外,如果集合实现了Iterable,您可以使用迭代器对集合进行迭代:

List<Integer> list;

Iterator<Integer> iterator = list.iterator();

while(someCondition){
    if(someOtherContion){
        Integer next = iterator.next();
    }
}

【讨论】:

  • 感谢您的快速回复!我不知道为什么我一开始没有想到这个哈哈
【解决方案2】:

您可以在循环中操纵i...这是不可取的,但可以这样做:-)

for (int i = 0; i < list.size(); i++) {
      Object o =  list.get(i);
      if (aCondition) {
        i--; //or somthing
      }
}

【讨论】:

    【解决方案3】:

    根本不要在集合中使用 For Each 元素。

    创建一个循环,声明您自己的迭代器,从 0 开始直到集合 Count 属性值,并使用比较数字组件作为条件测试器。

    可以使用显式迭代器值(按索引获取项目)和使用附加固定偏移量的相对项目来访问集合中的当前项目。

    【讨论】:

      猜你喜欢
      • 2010-10-03
      • 2012-05-17
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      • 2011-08-29
      • 2022-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多