0

This is what I want to achieve:

    public ArrayList<Point> startPoints = new ArrayList<Point>();
    public ArrayList<Point> endPoints = new ArrayList<Point>();

            for (Point startPoint : startPoints) { // <-- How do I do I do 2 at the same time?
                 g.fillOval(startPoint .x, startPoint.y, 10, 10);
                 g.drawLine(startPoint .x, startPoint.y, endPoint.x, endPoint.y);
            }

6 Answers6

4

use a "normal" for with an index i.

// if list1 and list2 have the same length
for(int i = 0;i<list1.size();i++){
   list1.get(i); // do something with that
   list2.get(i); // do something else with that
}
L.Butz
  • 2,466
  • 25
  • 44
0

Try to use normal for loop instead of foreach

user123454321
  • 1,028
  • 8
  • 26
0

If you are unable to change the data structures:

for (int i = 0; i < startPoints.size() && i < endPoints.size(); i++) {
    Point startPoint = startPoints.get(i);
    Point endPoint = endPoints.get(i);
    g.fillOval(startPoint.x, startPoint.y, 10, 10);
    g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);

}
azz
  • 5,852
  • 3
  • 30
  • 58
0

I would recommend, instead of relying on iteration to successfully stay in synch, to use a single Line class that contains two points. For each start and end point construct your Line object and insert it into an arraylist.

To get them out just iterate as follows:

for (Line line : lines) { // <-- How do I do I do 2 at the same time?
     g.fillOval(line.getStartPoint().x, line.getStartPoint().y, 10, 10);
     g.drawLine(line.getStartPoint().x, line.getStartPoint().y, line.getEndPoint().x, line.getEndPoint.y);
}
nanofarad
  • 40,330
  • 4
  • 86
  • 117
0

You cannot do both at the same time using the 'foreach' for loop you have.

If you are sure the Lists are both the same size then use the loop:

        for (int i = 0; i < startPoints.size(); i++) { // <-- How do I do I do 2 at the same time?
             Point startPoint = startPoints.get(i);
             Point endPoint = endPoints.get(i);
             g.fillOval(startPoint .x, startPoint.y, 10, 10);
             g.drawLine(startPoint .x, startPoint.y, endPoint.x, endPoint.y);
        }
rolfl
  • 17,539
  • 7
  • 42
  • 76
0

Since your data (startPoint and endPoint) are related - put them within another class (say MyVector) that will have startPoint and endPoint members (of type Point). Having such structure you iterate over list of MyVector objects.

Artur
  • 7,038
  • 2
  • 25
  • 39