【问题标题】:How to iterate through an ArrayList of integer? [closed]如何遍历整数的ArrayList? [关闭]
【发布时间】:2016-07-06 03:59:36
【问题描述】:

我有一个 ArrayList of Integer{1, 3, 4, 5 , 6}

如何遍历ArrayList,以便在每个循环中以这种方式打印出值?

1 and 3  
1 and 4  
1 and 5  
1 and 6  
3 and 4  
3 and 5  
3 and 6  
4 and 5  
4 and 6  
5 and 6 

我尝试执行 foreach 循环,然后执行 for 循环并在下一个之后删除一个对象,但遇到 ConcurrentModificationException。任何帮助将不胜感激!

【问题讨论】:

  • 向我们展示您的尝试。
  • 嵌套循环+如果pair是相同的值则省略
  • 为什么需要从列表中删除元素?那是实际需求的一部分吗?显示您的代码。
  • 哇。那些反对票。我实际上是在尝试解决一个问题,而这个问题解决了部分问题。我将在解决问题后发布问题。如果你们有兴趣解决它,我可能会在这里发布整个问题。看看你们想出什么解决方案会很有趣。如果您有兴趣,请点赞。
  • 如果您有兴趣,请在下面添加评论

标签: java arraylist


【解决方案1】:

我想这就是你想要的 - 迭代并删除第一个元素

为避免ConcurrentModificationException 在迭代和删除元素时使用标准的老式 for 循环而不是 foreach。

do
        {
            for (int j = 1; j < list.size(); j++)
            {
                System.out.println(list.get(0) + " and " + list.get(j));
            }
            list.remove(0);
        }
        while (list.size() != 0);

【讨论】:

  • 我怎么能忘记老式的while循环!这就是我现在需要的。谢谢老兄!
  • 如果有帮助,您应该接受答案。
  • 我是否可以在 for 循环中添加一个“打破循环”的 if 条件?
  • 是的,你绝对可以根据你的情况打破循环。
【解决方案2】:

这段代码应该可以工作:

   for (int i = 0; i < list.size() - 1; i++) {
        for (int j = i + 1; j < list.size(); j++) {
            System.out.println(list.get(i) + " and " + list.get(j));
        }
    }

【讨论】:

  • 问题是removeConcurrentModificationException
猜你喜欢
  • 1970-01-01
  • 2013-12-07
  • 2021-09-14
  • 2019-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-28
  • 2014-09-16
相关资源
最近更新 更多