-3

How can I rewrite these loops using foreach?

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

P.S. public CopyOnWriteArrayList<Ball> bList = new CopyOnWriteArrayList<Ball>();

Nikita Kalugin
  • 682
  • 2
  • 14
  • 37
  • 2
    What have you tried? What specifically do you need help with? – Carcigenicate Apr 26 '18 at 11:25
  • 2
    For the syntax see [here](https://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work), for the use cases have a look [here](https://stackoverflow.com/questions/18078354/use-a-for-loop-or-a-for-each-loop) – vincrichaud Apr 26 '18 at 11:28
  • foreach doesn't have loop counters so you might not be able to use a foreach in this case since your inner loop counter depends on the outer loop counter. – Erik Apr 26 '18 at 11:33
  • @Carcigenicate I'm trying to remove two objects (balls) from the collection at the time they are colliding. I use [this](https://ideone.com/2e9tzF). But there were a lot of errors "index out of bounds". And I'm trying to use foreach for this – Nikita Kalugin Apr 26 '18 at 11:44
  • @Carcigenicate And one more question. Can i use bList.remove(item); like this `for (Ball item : bList) { bList.remove(item); }` – Nikita Kalugin Apr 26 '18 at 11:49
  • 1
    The error "out of bound" happened because you do `j=i+1`. For the last i (list.size()-1), you have j=i+1 (list.size). So it violates the for because j is never lower than the list size. And when you'll do list.get(j) there is no element at this index – vincrichaud Apr 26 '18 at 11:53
  • 1
    If you want to remove object from the list while you iterate through the list, use an iterator to iterate. – vincrichaud Apr 26 '18 at 11:54

1 Answers1

1

You can use syntax with labels and int counters.

My example with String class instead of Ball:

CopyOnWriteArrayList<String> bList = new CopyOnWriteArrayList<String>();
    bList.add("1");
    bList.add("2");
    bList.add("3");
    bList.add("4");
    bList.add("5");

int i = 0;
    for (String s : bList) {
        System.out.println("outer: " + s);
        int j = 0;
        l: for (String s2 : bList) {
            while(j < i) {
                j++;
                continue l;
            }
            System.out.println("inner: " + s2);
        }
        i++;
    }

Output will be:

outer: 1
inner: 1
inner: 2
inner: 3
inner: 4
inner: 5
outer: 2
inner: 2
inner: 3
inner: 4
inner: 5
outer: 3
inner: 3
inner: 4
inner: 5
outer: 4
inner: 4
inner: 5
outer: 5
inner: 5

You can't modify collection in such conditions. I mean you can't remove any element from the collection while iterating through it.

I would like to suggest you to put all the collisions in some data structure, like ArrayList and remove elements AFTER iteration(loops).

Dmitrii Cheremisin
  • 1,498
  • 10
  • 11