gpt4 book ai didi

java - 不同类型的for循环结构

转载 作者:行者123 更新时间:2023-11-30 07:48:46 25 4
gpt4 key购买 nike

我见过的所有 for 循环基本上如下所示:

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

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

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

最佳答案

 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.

更多详细信息here

关于java - 不同类型的for循环结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33560408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com