Clone an Iterator in Java?

后端 未结 3 2015
再見小時候
再見小時候 2021-01-17 08:52

In a game I have a list of players, let\'s say like this:

LinkedList players = new LinkedList();

I want to let

3条回答
  •  长发绾君心
    2021-01-17 09:27

    In addition to aix answer, I'd like to point out that however you create an iterator starting at a specific index, it's bound to be a linear operation. If it wasn't, you would be able to do arbitrary access to the list in constant time using

    elementN = createIterator(linkedList, N).next();
    

    which would be contradictory.

    In your situation I therefore believe that the most efficient solution would actually be to do

    List tmp = new ArrayList(players);
    for (int p1 = 0; p1 < tmp.size(); p1++)
        for (int p2 = p1+1; p2 < tmp.size(); p2++)
            System.out.println("Interact: " + tmp.get(p1) + ", " + tmp.get(p2));
    

    Note however, that it is still the same complexity as the solution by aix; O(n2) but probably with a smaller constant factor.

提交回复
热议问题