Clone an Iterator in Java?

后端 未结 3 2016
再見小時候
再見小時候 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:18

    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;
    }
    

提交回复
热议问题