// check if the first segment and the last segment intersects.
Coordinate[] firstSeg = new Coordinate[2];
firstSeg[0] = arrayList.get(0);
firstSeg[1] = arrayList.get(1);
LineString first = gf.createLineString(firstSeg);
Coordinate[] lastSeg = new Coordinate[2];
lastSeg[0] = arrayList.get(arrayList.size() - 2);
lastSeg[1] = arrayList.get(arrayList.size() - 1);
LineString last = gf.createLineString(lastSeg);
Coordinate intersectionCoord;
if (first.intersects(last)) {
intersectionCoord = first.intersection(last).getGeometryN(0).getCoordinate();
if (!lastSeg[0].equals2D(intersectionCoord) && !lastSeg[1].equals2D(intersectionCoord)) {