Java 将增强的For循环转换为标准循环
我总是很难将增强的Java 将增强的For循环转换为标准循环,java,for-loop,foreach,Java,For Loop,Foreach,我总是很难将增强的for循环转换为标准的for循环。下面是增强的for循环,我想将其更改为标准的for循环结构: for (Thing cp: getPerson().getEnemy().getMinions()) { if (cp.canMoveTo(this.getLocation()) && cp.getLocation() != null) { return true; } }
for
循环转换为标准的for
循环。下面是增强的for
循环,我想将其更改为标准的for
循环结构:
for (Thing cp: getPerson().getEnemy().getMinions())
{
if (cp.canMoveTo(this.getLocation()) && cp.getLocation() != null)
{
return true;
}
}
return false;
}
如何将其更改为标准的for
循环?可以循环数组和任何类型的对象,因此答案取决于getMinions
是否返回数组或Iterable
对象
如果返回数组,则:
Thing[] minions = getPerson().getEnemy().getMinions();
for (int i = 0; i < minions.length; ++i) {
Thing cp = minions[i];
// ...
}
getMinions()
的返回类型是什么?
Iterator<Thing> it = getPerson().getEnemy().getMinions().iterator();
while (it.hasNext()) {
Thing cp = it.next();
// ...
}