More than one list in the same loop

2

Can I put more than one list in the same loop ? for example, you can put more than one variable in for :

for (int a, b; a<10 b<20; a++ b++) {
   .......
}

Then I wanted to put more than one list in the same foreach :

for(String s: lista) {

}
    
asked by anonymous 24.03.2018 / 22:17

1 answer

3

It's not possible, because it does not make much sense.

The first is possible, but the syntax that is wrong would look like this:

for (int a = 0, b = 0; a < 10 && b < 20; a++, b++)
    listaA[a] ...
    listaB[b] ...

But you will not do what you want. He will not go from 0 to 10 and 0 from 20. He will walk from 0 to 10 and finish. If you use || instead of && , then you will do the same, when you reach the eleventh element you will be picking up something that should not, and will probably break the application.

This only works if the lists are the same size and you want to scroll the same way, something like this:

for (int a = 0, b = 0; a < 10 && b < 10; a++, b++)
    listaA[a] ...
    listaB[b] ...

But in most cases it would not even require two variables, it could just be:

for (int a = 0; a < 10; a++)
    listaA[a] ...
    listaB[a] ...

In the second example, there is no way to do it, and this is one of the reasons to have for "simple".

In fact, you seldom need to go through two lists at the same time. If we knew the real need there we could give a better solution.

    
24.03.2018 / 23:04