Form a loop with previous and next I have a class Edge which looks something like this:

class Edge {

    Edge previous;
    Edge Next;

}


I have edges in an ArrayList. They have to form a loop, as in the last one is connected to the first one.

This is what I have:

    Edge previous, current, next;

    previous = edges.get(edges.size()-1);

    for (int i = 0; i &lt; edges.size(); i++) {
        current = edges.get(i);
        next = i+1 == edges.size() ? edges.get(0) : edges.get(i+1);

        current.previousEdge = previous;
        current.nextEdge = next;

        previous = current;
    }


I only have the idea that this could be written clearer than it is now.
You can use a for-each iterator instead of using indexes.
It would be somewhat simpler, like this:

Edge previous = edges.get(nodeList.size() - 1);
for (Edge edge : edges) {
    edge.previous = previous;
    previous.next = edge;
    previous = edge;
}




Suppose the initial list of edges is not in an ArrayList which allows quick random access but another kind of iterable. Then, you could rewrite this way without accessing any element by index:

Iterator&lt;Edge&gt; iter = edges.iterator();

Edge first = iter.next();
Edge previous = first;
Edge edge = null;

while (iter.hasNext()) {
    edge = iter.next();
    edge.previous = previous;
    previous.next = edge;
    previous = edge;
}

if (edge != null) {
    edge.next = first;
    first.previous = edge;
}