| 3 | import java.util.Iterator; |
| 4 | |
| 5 | public class CircularArray<T> implements Iterable<T> { |
| 6 | private T[] items; |
| 7 | private int head = 0; |
| 8 | |
| 9 | public CircularArray(int size) { |
| 10 | items = (T[]) new Object[size]; |
| 11 | } |
| 12 | |
| 13 | private int convert(int index) { |
| 14 | if (index < 0) { |
| 15 | index += items.length; |
| 16 | } |
| 17 | return (head + index) % items.length; |
| 18 | } |
| 19 | |
| 20 | public void rotate(int shiftRight) { |
| 21 | head = convert(shiftRight); |
| 22 | } |
| 23 | |
| 24 | public T get(int i) { |
| 25 | if (i < 0 || i >= items.length) { |
| 26 | throw new java.lang.IndexOutOfBoundsException("Index " + i + " is out of bounds"); |
| 27 | } |
| 28 | return items[convert(i)]; |
| 29 | } |
| 30 | |
| 31 | public void set(int i, T item) { |
| 32 | items[convert(i)] = item; |
| 33 | } |
| 34 | |
| 35 | public Iterator<T> iterator() { |
| 36 | return new CircularArrayIterator<T>(this); |
| 37 | } |
| 38 | |
| 39 | private class CircularArrayIterator<TI> implements Iterator<TI> { |
| 40 | private int _current = -1; |
| 41 | private TI[] _items; |
| 42 | |
| 43 | public CircularArrayIterator(CircularArray<TI> circularArray) { |
| 44 | _items = circularArray.items; |
| 45 | } |
| 46 | |
| 47 | @Override |
| 48 | public boolean hasNext() { |
| 49 | return _current < items.length - 1; |
| 50 | } |
| 51 | |
| 52 | @Override |
| 53 | public TI next() { |
| 54 | _current++; |
| 55 | TI item = (TI) _items[convert(_current)]; |
| 56 | return item; |
| 57 | } |
| 58 | |
| 59 | @Override |
| 60 | public void remove() { |
| 61 | throw new UnsupportedOperationException("Remove is not supported by CircularArray"); |
| 62 | } |
nothing calls this directly
no outgoing calls
no test coverage detected