1

All for-loops I've seen basically look like the following:

for(int i = 0; i < thing.length; i++){
    // Does this each iteration
}

But working on a project I came across (what I assume is) a different type of for-loop shown below. Can someone explain to me how this type of loop works? Does it have a name?

Component[] squares = getComponents();
for (Component c : squares)
{
    Square s = (Square) c;
    // Set the color of the squares appropriately
    int status = model.getOccupant(s.getRow(), s.getCol());
    if (status == P1)
    {
        s.setColor(P1_COLOR);
    }
    else
    {
        s.setColor(BACKGROUND_COLOR);
    }
}
Vivek Singh
  • 2,047
  • 11
  • 24
spencer.sm
  • 19,173
  • 10
  • 77
  • 88

1 Answers1

1
 for (Component c : squares)
    {
}

The is enhanced for=loop called for-each loop, introduced in release 1.5. Provides good readability of the code, but it misses the index.

When you see the colon (:), read it as “in.” Thus, the loop above reads as “for each element e in elements.” Note that there is no performance penalty for using the for-each loop, even for arrays.

More detailed information here

Community
  • 1
  • 1
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116