5

I have two arrays :

name[] and roll[]

Is there a way to traverse both arrays in one for each loop.Size of both arrays remain the same.

I know using two individual loops we can traverse and infact in one also its not a big deal, but I want something like this:

for(String n:name,int r:roll){
  //blah blah
}

Please shed some light thanks..... Ankur

Raghav
  • 4,590
  • 1
  • 22
  • 32
Ankur Verma
  • 5,793
  • 12
  • 57
  • 93
  • 2
    Worth a read: [The specification for the enhanced `for` loop](http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.14.2). This is a situation where the old-fashioned, index-based `for` loop will be needed instead. – T.J. Crowder Jun 29 '12 at 07:37

4 Answers4

7

No. You will have to use the old-fashioned

for(int index = 0; index < name.length; index++) {
  //blah blah with name[index] and roll[index]
}
Keppil
  • 45,603
  • 8
  • 97
  • 119
4

No. You can't traverse two same size array with a single for-each loop.

If you want to iterate both array in one loop then you will have to use traditional java for loop

Pramod Kumar
  • 7,914
  • 5
  • 28
  • 37
2
for(int i=0,len=name.length; i<len; i++) {
     String n = name[i];
     int r = roll[i];
}
Michael Besteck
  • 2,415
  • 18
  • 10
2

The for...each loop does not expose the index (intentionally, actually it does not even have one). You could use your own index if you are really bent on it, but you would be better off using the good old for loop with an index.

Here is how you would do it with your own index:

{
    int index = 0;
    for(String name : names) {
        // roll[index];
        ++index
    }
}

Also see this answer.

Community
  • 1
  • 1
Jeshurun
  • 22,940
  • 6
  • 79
  • 92