// Connor Moore // CSE 143, Summer 2016 // ArrayIntList can be used to store a list of integers. This version // assumes capacity can fit all elements public class ArrayIntList { private int[] data; // list of integers private int size; // current number of elements in the list // constructs an ArrayIntList with a capacity of 100 public ArrayIntList() { this(100); } // pre : capacity >= 0 // post: constructs an empty list with the given capacity public ArrayIntList(int capacity) { this.data = new int[capacity]; this.size = 0; } // pre : 0 <= index < size(), throws IndexOutOfBoundException otherwise // post: returns element at index public int get(int index) { checkBounds(index, size); return data[index]; } // pre : 0 <= index < size(), throws IndexOutOfBoundsException otherwise // post: sets the list at the index to the element public void set(int index, int element) { checkBounds(index, size); data[index] = element; } // post: adds element to the end of the list public void add(int element) { add(size, element); } // pre : 0 <= index <= size(), throws IndexOutOfBoundsException otherwise // post: element is inserted at index, shifting all elements to the right over // by one. public void add(int index, int element) { checkBounds(index, size + 1); for (int i = size - 1; i >= index; i--) { data[i + 1] = data[i]; } data[index] = element; size++; } // pre : 0 <= index < size(), throws IndexOutOfBoundsException otherwise // post: removes the element from the list at the index passed public void remove(int index) { for (int i = index; i < size - 1; i++) { data[i] = data[i + 1]; } size--; } // post: returns the size of the list public int size() { return size; } // post: returns true if the list is empty, false otherwise public boolean isEmpty() { // boolean zen return size == 0; } // post: returns the index of the element if the element is found in the list, // -1 otherwise public int indexOf(int element) { for (int i = 0; i < size; i++) { if (data[i] == element) { return i; } } return -1; } // post: returns true if the element is in the list, false otherwise public boolean contains(int element) { return indexOf(element) != -1; } // post: the list is emptied public void clear() { size = 0; } // post: creates a comma-separated, bracketed version of the list public String toString() { if (size == 0) { return "[]"; } else { String result = "[" + data[0]; for (int i = 1; i < size; i++) { result += ", " + data[i]; } result += "]"; return result; } } // If index < 0 or index >= upperBound, throws IndexOutOfBoundsException private void checkBounds(int index, int upperBound) { if (index < 0 || index >= upperBound) { throw new IndexOutOfBoundsException(); } } }