More than one list in the same loop

Asked

Viewed 429 times

3

I can put more than one list on it loop? for example, you can put more than one variable in a for:

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

So I wanted to put more than one list on it foreach:

for(String s: lista) {

}
  • 1

    I believe that this may not be possible in the second form.

  • 1

    Dude I think besides not being possible, it’s not a good idea. Why would you need this?

  • The right idea would be to create a class, structure, or object that you have, objects from the two lists, so you don’t manually do the relationship across all of it. But it is possible to accomplish this using iteration operators

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site

1 answer

4

It’s not possible, because it doesn’t make much sense.

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

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

But he won’t do what he wants. He won’t do one from 0 to 10 and the other from 0 to 20. He will do both from 0 to 10 and finish. Using || in place of &&, then you’ll do the same, when you get to the eleventh element you’ll be picking up something you shouldn’t, and you’ll probably break the application.

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

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

But in most cases it wouldn’t even need two variables, it might just be:

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

I put in the Github for future reference.

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

In fact it rarely needs to go through two lists at the same time. If we knew the real need then we could give a better solution.

  • If you use the || it is possible that listaA[a] ... is included within a block if (a < 10).

  • @ramaral yes, but besides complicating the code a little, it will make it slower. If you really need to run together, no problem, but if you don’t have to do business separately.

  • Besides, having to use if (a < 10), it would suffice to have a variable counter.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.