// An ArrayList stores an ordered list of elements int. public class ArrayIntList extends AbstractList { private int size; private int[] elementData; public static final int DEFAULT_CAPACITY = 10; // Initializes a new empty list with initial capacity of 10 integers. public ArrayIntList() { this(DEFAULT_CAPACITY); } // Initializes a new empty list with specified initial capacity. // pre: capacity > 0, throws IllegalArgumentException otherwise public ArrayIntList(int capacity) { if (capacity <= 0) { throw new IllegalArgumentException("capacity must be >= 0: " + capacity); } elementData = new int[capacity]; size = 0; // optional; size is initialized to 0 by default } // Inserts the given value into the list at the given index. // pre: 0 <= index <= size (can add at very end), throws // ArrayIndexOutOfBoundsException otherwise public boolean add(int index, int value) { checkIndex(index, 0, size); for (int i = size; i > index; i--) { elementData[i] = elementData[i - 1]; } elementData[index] = value; size++; return true; } // Returns the value at the given index. // pre: 0 <= index < size, throws ArrayIndexOutOfBoundsException otherwise public int get(int index) { checkIndex(index, 0, size - 1); return elementData[index]; } // Sets the given index to store the given value. // pre: 0 <= index < size, throws ArrayIndexOutOfBoundsException otherwise public void set(int index, int value) { checkIndex(index, 0, size - 1); elementData[index] = value; } // Removes and returns the value at the given index, shifting following values // over. // pre: 0 <= index < size, throws ArrayIndexOutOfBoundsException otherwise public int remove(int index) { checkIndex(index, 0, size - 1); int element = elementData[index]; for (int i = index; i < size - 1; i++) { elementData[i] = elementData[i + 1]; } size--; return element; } // Returns the number of elements in the list. public int size() { return size; } // Returns the first index of value or -1 if not found. public int indexOf(int value) { for (int i = 0; i < size; i++) { if (elementData[i] == value) { return i; } } return -1; } // Returns a String representation of the list consisting of the elements // in order, separated by commas and enclosed in square brackets. public String toString() { if (isEmpty()) { return "[]"; } else { String result = "["; for (int i = 0; i < size - 1; i++) { result += elementData[i] + ", "; } result += elementData[size - 1] + "]"; return result; } } // If index is not within specified bounds bounds, throws // ArrayIndexOutOfBoundsException private void checkIndex(int index, int min, int max) { if (index < min || index > max) { throw new ArrayIndexOutOfBoundsException("Invalid index " + index); } } }