-
Notifications
You must be signed in to change notification settings - Fork 23
/
DinerMenuIterator.java
56 lines (50 loc) · 1.63 KB
/
DinerMenuIterator.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
package Cafe;
import DinerAndPancakeHouseIterator.MenuItem;
import java.util.Iterator;
/**
* concrete Iterator that works for the Diner menu
*/
public class DinerMenuIterator implements Iterator {
MenuItem[] items;
// position maintains the current position of the iteration over the array
int position = 0;
/**
* takes the array of menu items we are going to iterate over the array
* @param items
*/
public DinerMenuIterator(MenuItem[] items) {
this.items = items;
}
public boolean hasNext() {
// we need to check not only if we are at the end of the array,
// but also it the next item is null, which indicates there are no more items
if (position >= items.length || items[position] == null) {
return false;
} else {
// true if there are more to iterate through
return true;
}
}
/**
* returns the next item in the array and increments the position
* @return
*/
public Object next() {
MenuItem menuItem = items[position];
position = position + 1;
return menuItem;
}
// we do need to implement remove()
public void remove() {
if (position <= 0) {
throw new IllegalStateException ("You can't remove an item you've done at least one next()");
}
// we just shift all the elements up one when remove() is called
if (items[position-1] != null) {
for (int i = position-1; i < (items.length-1); i++) {
items[i] = items[i+1];
}
items[items.length-1] = null;
}
}
}