2015-11-06 90 views
1

所有for循环,我基本上看到如下所示:不同类型的for循环结构

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

但在我碰到一个项目工作(我认为是),针对不同类型的如下所示。有人可以向我解释这种类型的循环是如何工作的吗?它有名字吗?

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); 
    } 
} 
+0

你google一下? – shaun

+1

如果你不知道它叫什么,很难谷歌的东西。但现在我知道了。谢谢,@Eran –

回答

1
for (Component c : squares) 
    { 
} 

的用于=环称为for-each循环,在释放 1.5引入增强。提供良好的代码可读性,但错过了索引。

当您看到冒号(:)时,请将其读为“in”。因此, 之上的循环显示为“对于元素中的每个元素e”。请注意,使用for-每个循环,即使对于数组。

更详细的信息here