# Compare ArrayLists / detect line intersections

Hello! I’m trying to write code that checks if any two lines drawn on the canvas have intersecting points.

Currently, I have an ArrayList of “Line” objects, each containing their own ArrayList of PVectors (“coords”). I want to compare the all of the PVectors in each of the Lines to see which of them match with each other.
I’ve tried using nested loops but the lines always end up comparing their own coordinates to themselves. How do I make it not do this? Is there a better way to do this? Thank you!

``````     for(Line l1: lines){
for (Line l2: lines){
for(PVector c1 : l1.coords){
for(PVector c2 : l2.coords){
if(c1.x==c2.x &&
c1.y== c2.y){
ellipse(c1.x,c1.y,50,50);
}
}
}
}
}
``````
1 Like

The answer is pretty simple :

``````for (int x = 0; x < lines.length; x++) {
for (int y = 0; y < lines.length; y++) {
if (x != y) {
if (lines[x].x == lines[y].x && lines[x].y == lines[y].y) {
ellipse(lines[x].x, lines[x].y);
}
}
}
}
``````

or with for each loops it would be this :

``````for (Line l1 : lines) {
for (Line l2 : lines) {
if (l1 != l2) {
if (l1.x == l2.x && l1.y == l2.y) {
ellipse(l1.x, l1.y);
}
}
}
}
``````
2 Likes

Oh duh, thank you. I had made it work in a convoluted way by checking if lines.indexOf(l1) != lines.indexOf(l2),

For a discussion and interactive example of line-line intersection, also see:

http://www.jeffreythompson.org/collision-detection/line-line.php

1 Like