// Pretty-much complete ArrayIntList class // NOTE: FOR HOMEWORK 1, DON'T USE THIS FILE AS YOUR STARTING POINT. // USE THE ArrayIntList.java LINK FROM THE "Homework" PAGE. public class ArrayIntList { // class constant for default list capacity public static final int DEFAULT_CAPACITY = 10; // encapsulated -- clients can't break them private int[] elementData; private int size; // constructor 1: initializes a new list that stores up to 10 elements. public ArrayIntList() { // calls the (int capacity) constructor this(DEFAULT_CAPACITY); } // constructor 2: initializes a new list that stores up to the // given number of elements. // pre: capacity > 0 public ArrayIntList(int capacity) { elementData = new int[capacity]; size = 0; } // accessor - a method that gives the client information about the object. // post: returns the number of elements in the list. public int size() { return size; } // pre: 0 <= index <= size-1 // post: returns the element at the given index. public int get(int index) { return elementData[index]; } // pre: size < elementData.length - 1 (there is room in the array) // post: adds an integer to the end of this list. public void add(int value) { elementData[size] = value; size++; } // pre: size < elementData.length - 1 (there is room in the array) // pre: 0 <= index <= size // post: inserts an integer to this list at the specified index. public void add(int index, int value) { for (int i = size - 1; i >= index; i--) { elementData[i+1] = elementData[i]; } elementData[index] = value; size++; } // pre: 0 <= index <= size-1 // post: removes the value at the given index, shifting subsequent values left. public void remove(int index) { // shift elements to the left (cover the gap) for (int i = index + 1; i <= size - 1; i++) { elementData[i-1] = elementData[i]; } elementData[size - 1] = 0; // reduce the size size--; } // returns a String representation of the list in human-readable form. 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; } } }