MyList.java
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.util.LinkedList; import java.util.ListIterator; /** * * @param <T> * */ public class MyList<T> extends LinkedList<T>{ public ListIterator<T> MyListIterator(){ return new MyListIterator<>(this); } } |
MyListIterator.java
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 |
import java.util.ListIterator; import java.util.NoSuchElementException; public class MyListIterator<T> implements ListIterator<T> { private MyList list; // current position of iterator // this position is returnd if next() is called private int position; // last/previous element can be removed private boolean removeOK; // next() was called last private boolean nextCalled; // previous() was called last private boolean previousCalled; // last/previous element can be set private boolean setOK; public MyListIterator(MyList<T> list){ this.list = list; position = 0; removeOK = false; } @Override public boolean hasNext() { if(position < list.size()) return true; return false; } @Override public T next() { if(! hasNext()) throw new NoSuchElementException(); T result = (T) list.get(position); position++; removeOK = true; nextCalled = true; previousCalled = false; setOK = true; return result; } @Override public boolean hasPrevious() { return position > 0; } @Override public T previous() { if(!hasPrevious()) throw new NoSuchElementException(); position--; removeOK = true; previousCalled = true; nextCalled = false; setOK = true; return (T) list.get(position); } @Override public int nextIndex() { return position; } @Override public int previousIndex() { return position-1; } @Override public void remove() { if(!removeOK) throw new IllegalStateException(); if(nextCalled){ list.remove(position-1); position--; } if(previousCalled){ list.remove(position); } removeOK = false; setOK = false; // if first element is removed after previous was called, // position does not need to be updated } @Override public void set(T e) { if(!setOK) throw new IllegalStateException(); if(nextCalled) list.set(position-1, e); if(previousCalled) list.set(position, e); } @Override public void add(T e) { if(position <= list.size()){ list.add(position, e); position++; setOK = false; removeOK = false; } } } |