| 11 | package java.util; |
| 12 | |
| 13 | public class ArrayDeque<T> extends AbstractDeque<T> |
| 14 | implements Deque<T> { |
| 15 | private Object[] dataArray; |
| 16 | // both indexes are inclusive, except when size == 0 |
| 17 | private int startIndex; |
| 18 | private int endIndex; |
| 19 | private int size; |
| 20 | private int modCount; |
| 21 | |
| 22 | public ArrayDeque() { |
| 23 | this(16); |
| 24 | } |
| 25 | |
| 26 | public ArrayDeque(int intialSize) { |
| 27 | dataArray = new Object[intialSize]; |
| 28 | modCount = 0; |
| 29 | clear(); |
| 30 | } |
| 31 | |
| 32 | public ArrayDeque(Collection<? extends T> c) { |
| 33 | this(c.size()); |
| 34 | |
| 35 | addAll(c); |
| 36 | } |
| 37 | |
| 38 | private void copyInto(Object[] array) { |
| 39 | if (startIndex <= endIndex) { |
| 40 | // only one copy needed |
| 41 | System.arraycopy(dataArray, startIndex, array, 0, size); |
| 42 | } else { |
| 43 | int firstCopyCount = dataArray.length - startIndex; |
| 44 | System.arraycopy(dataArray, startIndex, array, 0, firstCopyCount); |
| 45 | System.arraycopy(dataArray, 0, array, firstCopyCount, endIndex + 1); |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | private void ensureCapacity(int newSize) { |
| 50 | if (dataArray.length < newSize) { |
| 51 | Object[] newArray = new Object[dataArray.length * 2]; |
| 52 | copyInto(newArray); |
| 53 | |
| 54 | dataArray = newArray; |
| 55 | startIndex = 0; |
| 56 | endIndex = size - 1; |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | @Override |
| 61 | public boolean offerFirst(T e) { |
| 62 | ensureCapacity(size() + 1); |
| 63 | modCount++; |
| 64 | |
| 65 | if (size > 0) { |
| 66 | // we don't need to move the head index for the first one |
| 67 | startIndex--; |
| 68 | if (startIndex < 0) { // wrapping to the end of the array |
| 69 | startIndex = dataArray.length - 1; |
| 70 | } |
nothing calls this directly
no outgoing calls
no test coverage detected