0

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);
        }
6
  • The first one ignores the last item in the collection, the 2nd hits all items. Why do you ask? What behavioral differences do you see? Commented Nov 3, 2016 at 2:24
  • I want to paint all the items in the ArrayList. The second one does it right: it paints all the shapes in order as you drag the mouse. The first one paints the shape as you drag the mouse, but it disappears on release. Then while you draw the second shape, the first shape reappears again. Commented Nov 3, 2016 at 2:26
  • Well your first for loop is broken. Commented Nov 3, 2016 at 2:27
  • Why do you include that - 1? as most tutorials would show you the correct way to loop. Commented Nov 3, 2016 at 2:29
  • I was thinking if there were 10 items (size = 10) and index starts at 0, then it starts counting at 0 until 9 (which is size = 10). Commented Nov 3, 2016 at 2:37

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help! You helped me solve the problem. I will accept your answer after 10 minutes. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.