import java.util.*; public class ArrayIntList implements IntList { private int[] elementData; // list of integers private int size; // current number of elements in the list public static final int DEFAULT_CAPACITY = 100; public ArrayIntList() { this(DEFAULT_CAPACITY); } public ArrayIntList(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("capacity: " + capacity); } elementData = new int[capacity]; size = 0; } public int size() { return size; } public int get(int index) { checkIndex(index); return elementData[index]; } public String toString() { if (size == 0) { return "[]"; } else { String result = "[" + elementData[0]; for (int i = 1; i < size; i++) { result += ", " + elementData[i]; } result += "]"; return result; } } public int indexOf(int value) { for (int i = 0; i < size; i++) { if (elementData[i] == value) { return i; } } return -1; } public boolean isEmpty() { return size == 0; } public boolean contains(int value) { return indexOf(value) >= 0; } public void add(int value) { add(size, value); } public void add(int index, int value) { if (index < 0 || index > size) { throw new IndexOutOfBoundsException("index: " + index); } ensureCapacity(size + 1); for (int i = size; i > index; i--) { elementData[i] = elementData[i - 1]; } elementData[index] = value; size++; } public void set(int index, int value) { checkIndex(index); elementData[index] = value; } public void clear() { size = 0; } public void remove(int index) { checkIndex(index); for (int i = index; i < size - 1; i++) { elementData[i] = elementData[i + 1]; } size--; } public Iterator iterator() { return new ArrayIntListIterator(); } private void checkIndex(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException("index: " + index); } } public void ensureCapacity(int capacity) { if (capacity > elementData.length) { int newCapacity = elementData.length * 2 + 1; if (capacity > newCapacity) { newCapacity = capacity; } elementData = Arrays.copyOf(elementData, newCapacity); } } private class ArrayIntListIterator implements Iterator { private int position; // current position within the list private boolean removeOK; // whether it's okay to remove now // pre : list != null // post: constructs an iterator for the given list public ArrayIntListIterator() { position = 0; removeOK = false; } // post: returns true if there are more elements left, false otherwise public boolean hasNext() { return position < size(); } // pre : hasNext() // post: returns the next element in the iteration public Integer next() { if (!hasNext()) { throw new NoSuchElementException(); } int result = get(position); position++; removeOK = true; return result; } // pre : next() has been called without a call on remove (i.e., at most one // call per call on next) // post: removes the last element returned by the iterator public void remove() { if (!removeOK) { throw new IllegalStateException(); } ArrayIntList.this.remove(position - 1); position--; removeOK = false; } } }