-
Notifications
You must be signed in to change notification settings - Fork 10
/
CircularArray.java
67 lines (53 loc) · 1.21 KB
/
CircularArray.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
import java.util.Iterator;
public class CircularArray<T> implements Iterable<T>{
/**
* @param args
*/
private T[] items;
private int head = 0;
public CircularArray(int size) {
items = (T[]) new Object[size];
}
private int convert(int index) {
if (index < 0) {
index += items.length;
}
return (head + index) % items.length;
}
public void rotate(int shiftRight) {
head = convert(shiftRight);
}
public T get(int i) {
if (i < 0 || i >= items.length) {
throw new java.lang.IndexOutOfBoundsException("...");
}
return items[convert(i)];
}
public void set(int i, T item) {
items[convert(i)] = item;
}
public Iterator<T> iterator() {
return new CircularArrayIterator<T>(this);
}
private class CircularArrayIterator<TI> implements Iterator<TI> {
private int _current = -1;
private TI[] _items;
public CircularArrayIterator(CircularArray<TI> array) {
_items = array.items;
}
@Override
public boolean hasNext() {
return _current < items.length - 1;
}
@Override
public TI next() {
_current++;
TI item = (TI) _items[convert(_current)];
return item;
}
@Override
public void remove() {
throw new UnsupportedOperationException("...");
}
}
}