java iterator复制,用Java克隆Iterator?

本文介绍了一种使用ListIterator实现的高效方法,使每个玩家仅与其他玩家交互一次,避免了重复和自身交互的情况。通过从指定位置开始迭代并获取当前位置信息,确保了每对玩家组合的唯一性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值