In a game I have a list of players, let's say like this:
LinkedList players = new LinkedList();
I want to let each player interact with each of the other players, so I write two nested loops:
Iterator i1 = players.iterator();
while (i1.hasNext()) {
String p1 = i1.next();
Iterator i2 = players.iterator();
// But I want to do this: Iterator i2 = i1.clone();
while (i2.hasNext()) {
String p2 = i2.next();
System.out.println("Interact: " + p1 + ", " + p2);
}
}
Since I only want each pair of players to interact once, I want to start the inner loop with the player after the outer loop's current player. So I want to clone the iterator, but that doesn't compile.
So, what should I do instead?
解决方案
The following will do it:
ListIterator i1 = players.listIterator(0);
while (i1.hasNext()) {
String p1 = i1.next();
ListIterator i2 = players.listIterator(i1.nextIndex());
while (i2.hasNext()) {
String p2 = i2.next();
System.out.println("Interact: " + p1 + ", " + p2);
}
}
It relies on the ListIterator's ability to start from the given position and to also know its current position.