// CSE 143, Winter 2011, Marty Stepp // An ArrayIntList object stores an ordered list of integers using // an unfilled array. // This is an unfinished "in-progress" version of the class. // We will work on it more in Tuesday's section and Wednesday's lecture. import java.util.*; // for Arrays public class ArrayIntList { private static final int INITIAL_CAPACITY = 10; // fields - the data inside each ArrayIntList object private int size; private int[] elementData; // Initializes a new empty list with initial capacity of 10 integers. public ArrayIntList() { size = 0; elementData = new int[INITIAL_CAPACITY]; } // Adds the given value to the end of the list. // If necessary, resizes the array to fit the value. public void add(int value) { // checkResize(); // elementData[size] = value; // size++; // just call the other add method (to remove redundancy) add(size, value); } // Inserts the given value into the list at the given index. // If necessary, resizes the array to fit the value. // For now we will assume that 0 <= index <= size. public void add(int index, int value) { checkResize(); // slide elements to the right to make room for (int i = size; i > index; i--) { elementData[i] = elementData[i - 1]; } // insert the value in the hole we just made elementData[index] = value; size++; } // Returns the value in the list at the given index. // For now we will assume that 0 <= index < size. public int get(int index) { return elementData[index]; } // Sets the given index to store the given value. // For now we will assume that 0 <= index < size. public void set(int index, int value) { elementData[index] = value; } // Returns the number of elements in the list. public int size() { return size; } // Returns true if the list does not contain any elements. public boolean isEmpty() { return size == 0; // "boolean zen" } // Removes the value from the given index, shifting following elements left // by 1 slot to cover the hole. // For now we will assume that 0 <= index < size. public void remove(int index) { for (int i = index; i <= size - 1; i++) { elementData[i] = elementData[i + 1]; } size--; } // A "private helper method" to resize the array if necessary. // Checks whether the list's array is full, and if so, // doubles its size so that more elements can be added. private void checkResize() { if (size == elementData.length) { // resize the array elementData = Arrays.copyOf(elementData, 2 * size); } } }