How can I make a copy of an iterator in Java?

前端 未结 3 1520
谎友^
谎友^ 2021-01-17 13:15

We have a list of elements and have a very simplistic collision detection where we check every object against every other object.

The check is commutative, so to avo

3条回答
  •  不知归路
    2021-01-17 14:16

    You can do this with ListIterator:

    for(ListIterator outer = list.listIterator(); outer.hasNext() ; ) {
        O oVal = outer.next();
        for(ListIterator inner = list.listIterator(outer.nextIndex()); inner.hasNext(); ) {
             Test(oVal, inner.next());
        }
    }
    

    For a linked list (which has slow index access) the list.listIterator(index) still needs to iterate to the right place, though. But this way it is only O(n²) (and you can't get better than this) instead of O(n³) like the index-access in the other answers then. (You might be even faster if you copy your list first to an array, but it is only a constant factor here.)

    Of course, if you usually need index-based access (or this iterator-cloning), you would better use an array-based list (or a custom list whose iterator supports cloning).

提交回复
热议问题