有人可以帮我指出这两个 for 循环之间的区别吗?他们看起来可能在做同样的事情,但事实并非如此。
for(int i = 0; i < shapes.size() - 1; i++) {
Graphics2D g2d = (Graphics2D) g;
shapes.get(i).paint(g2d);
}
如何编写没有 i(索引)的第一个 for 循环?
for(Shape shape : shapes) {
Graphics2D g2d = (Graphics2D) g;
shape.paint(g2d);
}
最佳答案
They look like they might be doing the same thing, but they aren't.
第一个循环忽略集合中的最后一个形状,而第二个循环则命中所有项目。要解决第一个问题,请删除 - 1
部分。即更改为:
Graphics2D g2d = (Graphics2D) g;
for(int i = 0; i < shapes.size(); i++) {
shapes.get(i).paint(g2d);
}
关于java - Java Swing 中使用索引的 For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40392840/