-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathPeekingIterator.java
More file actions
76 lines (67 loc) · 2.13 KB
/
PeekingIterator.java
File metadata and controls
76 lines (67 loc) · 2.13 KB
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
// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
class PeekingIterator implements Iterator<Integer> {
Iterator<Integer> iterator;
Integer peek;
public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
this.iterator = iterator;
}
// Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
if (peek == null) peek = iterator.next();
return peek;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
if (peek != null) {
Integer res = peek;
peek = null;
return res;
} else return iterator.next();
}
@Override
public boolean hasNext() {
if (peek != null) return true;
else return iterator.hasNext();
}
}
//Generic version
// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
class PeekingIterator<E> implements Iterator<E> {
Iterator<E> iterator;
E peek;
public PeekingIterator(Iterator<E> iterator) {
// initialize any member here.
this.iterator = iterator;
}
// Returns the next element in the iteration without advancing the iterator.
public E peek() {
if (peek == null) peek = iterator.next();
return peek;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public E next() {
if (peek != null) {
E res = peek;
peek = null;
return res;
} else return iterator.next();
}
@Override
public boolean hasNext() {
if (peek != null) return true;
else return iterator.hasNext();
}
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
PeekingIterator<String> it = new PeekingIterator<>(list.iterator());
System.out.println(it.peek());
}
}
//