user2898147
user2898147

Reputation:

How do I iterate on these lists at the same time?

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);
            }

Upvotes: 0

Views: 139

Answers (6)

Artur
Artur

Reputation: 7267

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.

Upvotes: 0

rolfl
rolfl

Reputation: 17707

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);
        }

Upvotes: 0

nanofarad
nanofarad

Reputation: 41281

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);
}

Upvotes: 0

azz
azz

Reputation: 5940

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);

}

Upvotes: 0

user123454321
user123454321

Reputation: 1058

Try to use normal for loop instead of foreach

Upvotes: 0

L.Butz
L.Butz

Reputation: 2616

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
}

Upvotes: 4

Related Questions