【问题标题】:Is there an algorithm for iterating around an ArrayList in a circle?是否有一种算法可以围绕 ArrayList 循环迭代?
【发布时间】:2020-02-07 06:46:35
【问题描述】:

也就是说,在我到达工作表末尾的那一刻,下一个元素为零。

【问题讨论】:

  • 请添加更多关于你想要做什么的细节。
  • 工作表?什么零?请澄清。

标签: java list iterator


【解决方案1】:

是的,有:

考虑以下代码:

for (int i = 0; i < 100; i++) {
   // Output will be: 0,1,2,3,4,5,6,7;0,1,2,3,4,5,6,7;...
   System.out.println(i % 8);
}

【讨论】:

    【解决方案2】:

    假设您已经声明并填充了一个ArrayList,我将其称为list,那么您只需以列表大小为模进行迭代。具体怎么写取决于你想做什么。

    1) 永远循环下去:

    int index = 0;
    while (true) {
        value = list.get(index);
        … process value here …
        index = (index + 1) % list.size();
        // or equivalently to previous line: if (++index >= list.size) index = 0;
    }
    

    2) 仅循环一次列表,但从任意点开始 base:

    for (int offset = 0; offset < list.size(); offset++) {
        int index = (base + offset) % list.size();
        value = list.get(index);
        … process value here …
    }
    

    等等……

    方法可以设计为使用显式迭代器而不是索引,但这完全取决于您想要实现的目标。

    【讨论】:

      【解决方案3】:

      试试这个:

      ArrayList<Object> list = new ArrayList<>(); // + add some values to the list
      
      for (int i = 0; i < list.size(); i++) {
          someMethod();
          if (some condition) {
              break; // you need to add some break condition, otherwise, this will be an infinite loop
          }
          if (i == list.size() - 1) {
              i = -1;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2020-03-18
        • 1970-01-01
        • 2011-12-29
        • 2020-11-27
        • 1970-01-01
        • 2011-03-28
        • 1970-01-01
        • 1970-01-01
        • 2022-01-02
        相关资源
        最近更新 更多