Rain Rain - 1 month ago 17
Java Question

For loops in Java Swing using index

Can someone help me point at the difference between these two for loops? They look like they might be doing the same thing, but they aren't.

for(int i = 0; i < shapes.size() - 1; i++) {
Graphics2D g2d = (Graphics2D) g;
shapes.get(i).paint(g2d);
}


How do I write my first for loop without the i (index)?

for(Shape shape : shapes) {
Graphics2D g2d = (Graphics2D) g;
shape.paint(g2d);
}

Answer

They look like they might be doing the same thing, but they aren't.

The first loop ignores the last shape in the collection, while the 2nd loop hits all items. To fix the first, get rid of the - 1 part. i.e., change to:

Graphics2D g2d = (Graphics2D) g;
for(int i = 0; i < shapes.size(); i++) {
    shapes.get(i).paint(g2d);
}