// Helene Martin, CSE 143 // An ArrayIntList stores an ordered list of integers. // Today's version added: //* generics so that we can store any type of value //* a common abstract class and interface so that ArrayList and LinkedList can // be used interchangeably in client code. import java.util.Arrays; public class ArrayList extends AbstractList { private int size; private E[] elementData; public static final int DEFAULT_CAPACITY = 10; // Initializes a new empty list with initial capacity of 10 integers. public ArrayList() { // elementData = new int[10]; this(DEFAULT_CAPACITY); } // Initializes a new empty list with specified initial capacity. // pre: capacity > 0, throws IllegalArgumentException otherwise public ArrayList(int capacity) { if (capacity <= 0) { throw new IllegalArgumentException("capacity must be >= 0: " + capacity); } elementData = (E[]) (new Object[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 void add(int index, E value) { checkIndex(index, 0, size); if (size == elementData.length) { elementData = Arrays.copyOf(elementData, size * 2); } for (int i = size; i > index; i--) { elementData[i] = elementData[i - 1]; } elementData[index] = value; size++; } // Returns the value at the given index. // pre: 0 <= index < size, throws ArrayIndexOutOfBoundsException otherwise public E 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, E value) { checkIndex(index, 0, size - 1); elementData[index] = value; } // Removes the value at the given index, shifting following values over. // pre: 0 <= index < size, throws ArrayIndexOutOfBoundsException otherwise public void remove(int index) { checkIndex(index, 0, size - 1); for (int i = index; i < size - 1; i++) { elementData[i] = elementData[i + 1]; } size--; } // 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(E value) { for (int i = 0; i < size; i++) { if (elementData[i].equals(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); } } }