In a game I have a list of players, let\'s say like this:
LinkedList players = new LinkedList();
I want to let
For a solution that avoids the linear cost associated to listIterator(int)
(NPE's answer), see my answer to a similar question.
In brief, as long as you don't care about the order the list is visited, you can start the outer loop from the last element and iterate back, and start the inner loop from the first element and iterate forward until the two iterators meet. The call to list.listIterator(list.size()) is fast because list is a LinkedList, i.e. a doubly-linked list, and accessing the last element does not require iterating through the list. See example below:
public static int iterRevIterator(List list) {
int sum = 0;
for(ListIterator outer = list.listIterator(list.size()); outer.hasPrevious(); ) {
Integer oVal = outer.previous();
for(ListIterator inner = list.listIterator(); inner.nextIndex() <= outer.previousIndex(); ) {
sum += oVal * inner.next();
}
}
return sum;
}