Search code examples
javaiteratorlistiterator

Retrieve both current and previous elements using Iterator in Java


I have an ArrayList in my Java code and I would like to retrieve both its current and previous elements.

This is the code I made :

    List<Graph> graphs = new ArrayList<Graph>();
    graphs.addAll(bestGraphs.values());
    ListIterator<Graph> listItr = graphs.listIterator();
    while(listItr.hasNext()) {
        if(!listItr.hasPrevious()) {
            listItr.next();
        } else {
            Graph g1 = listItr.previous();
            Graph g2 = listItr.next();
            croisementGraphs(g1, g2);
            listItr.next();
        }
    }

croisementGraphs(g1, g2); is a function that should take both the current and the previous elements (graphs) of the ArrayList.

The problem here is that both variables g1 and g2 point to the same element.

When I read the Javadoc related to the previous() function, it says :

(Note that alternating calls to next and previous will return the same element repeatedly.)

What should I do in this case ?

Thanks!


Solution

  • You can use your solution, just take the actual next item:

    Graph g1 = listItr.previous();
    listItr.next();
    Graph g2 = listItr.next();
    croisementGraphs(g1, g2);
    

    And I think that you should read about the iterators, I am afraid you don't understand how they work. I'll try to explain it briefly:

    • Iterators are located between items, not at them
    • When next or previous is called iterators return an item they just "walked over"

    Small example: lets take a list of a few items: [1,2,3], and present it in the next form: [.1.2.3.], lets show where iterator is by placing a letter x there. Now some actions and corresponding state changes:

    ListIterator x = list.listIterator(); // [x1.2.3.] 
    x.next(); // [.1x2.3.], returns 1
    x.previous(); // [x1.2.3.], returns 1
    x.next(); // [.1x2.3.], returns 1
    x.next(); // [.1.2x3.], returns 2