blob: 45d78ddf8ee663ac0ef43bfe27aa43ae44c32b0b (
plain) (
blame)
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
|
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.annotation;
import java.util.ListIterator;
/**
* @author <a href="mailto:einarmr@yahoo-inc.com">Einar M R Rosenvinge</a>
*/
class PeekableListIterator<E> implements ListIterator<E> {
private E next;
private ListIterator<E> base;
boolean traversed = false;
private int position = -1;
PeekableListIterator(ListIterator<E> base) {
this.base = base;
this.traversed = false;
}
@Override
public boolean hasNext() {
return next != null || base.hasNext();
}
@Override
public E next() {
if (next == null) {
E n = base.next();
position++;
return n;
}
E retval = next;
next = null;
position++;
return retval;
}
@Override
public boolean hasPrevious() {
throw new UnsupportedOperationException();
}
@Override
public E previous() {
throw new UnsupportedOperationException();
}
@Override
public int nextIndex() {
throw new UnsupportedOperationException();
}
@Override
public int previousIndex() {
throw new UnsupportedOperationException();
}
@Override
public void remove() {
if (position < 0) {
//we have not next'ed the iterator, cannot do this:
throw new IllegalStateException("Cannot remove() before next()");
}
if (next != null) {
//we have already gone one step ahead. must back up two positions and then remove:
base.previous();
base.previous();
base.remove();
} else {
base.remove();
}
next = null;
}
@Override
public void set(E e) {
if (position < 0) {
//we have not next'ed the iterator, cannot do this:
throw new IllegalStateException("Cannot set() before next()");
}
if (next != null) {
//we have already gone one step ahead. must back up two positions and then remove:
base.previous();
base.previous();
}
base.set(e);
next = null;
}
@Override
public void add(E e) {
if (next != null) {
//we have already gone one step ahead. must back up one position and then add:
base.previous();
}
base.add(e);
next = null;
}
public E peek() {
if (next == null && base.hasNext()) {
next = base.next();
}
return next;
}
}
|