Using ListIterator to move back and forth over a LinkedList in Java

前端 未结 3 650
甜味超标
甜味超标 2021-02-18 17:26

I have a LinkedList over which I need to iterate back and forth multiple times. I am using it to keep track of a series of pages in a workflow that will be created dynamically.

3条回答
  •  渐次进展
    2021-02-18 17:45

    This should do your job:

    public class Main {
        public static void main(String[] args) {
            final LinkedList list = new LinkedList ();
    
            list.add ("1"); list.add ("2"); list.add ("3"); list.add ("4");
    
            final MyIterator it = new MyIterator (list.listIterator());
    
            System.out.println(it.next());
            System.out.println(it.next ());
            System.out.println(it.next ());
            System.out.println(it.previous ());
            System.out.println(it.previous ());
            System.out.println(it.next ());
        }
    
        public static class MyIterator {
    
            private final ListIterator listIterator;
    
            private boolean nextWasCalled = false;
            private boolean previousWasCalled = false;
    
            public MyIterator(ListIterator listIterator) {
                this.listIterator = listIterator;
            }
    
            public T next() {
                nextWasCalled = true;
                if (previousWasCalled) {
                    previousWasCalled = false;
                    listIterator.next ();
                }
                return listIterator.next ();
            }
    
            public T previous() {
                if (nextWasCalled) {
                    listIterator.previous();
                    nextWasCalled = false;
                }
                previousWasCalled = true;
                return listIterator.previous();
            }
    
        }   
    }
    

    And a fiddle for it.

提交回复
热议问题