用Java克隆Iterator? [英] Clone an Iterator in Java?
本文介绍了用Java克隆Iterator?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在游戏中我有一个玩家列表,让我们这样说:
In a game I have a list of players, let's say like this:
LinkedList<String> players = new LinkedList<String>();
我想让每个玩家与其他玩家互动,所以我写了两个嵌套循环:
I want to let each player interact with each of the other players, so I write two nested loops:
Iterator<String> i1 = players.iterator();
while (i1.hasNext()) {
String p1 = i1.next();
Iterator<String> i2 = players.iterator();
// But I want to do this: Iterator<String> 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.
那么,我该怎么做呢?
推荐答案
以下将执行此操作:
ListIterator<String> i1 = players.listIterator(0);
while (i1.hasNext()) {
String p1 = i1.next();
ListIterator<String> i2 = players.listIterator(i1.nextIndex());
while (i2.hasNext()) {
String p2 = i2.next();
System.out.println("Interact: " + p1 + ", " + p2);
}
}
它依赖于 ListIterator
能够从给定位置开始并知道其当前位置。
It relies on the ListIterator
's ability to start from the given position and to also know its current position.
这篇关于用Java克隆Iterator?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文