// CSE 143, Homework 1 (SortedIntList) // An ArrayIntList object can be used to store a list of integers. // This file is provided to you by the instructor. // // You should not modify this file! Your code will be tested with an // unmodified version of this class. public class ArrayIntList { public static final int DEFAULT_CAPACITY = 100; // These data fields are declared 'protected' to allow SortedIntList to access them. protected int[] elementData; // list of integers protected int size; // current number of elements in list // Constructs an empty list of a default capacity. public ArrayIntList() { this(DEFAULT_CAPACITY); } // Constructs an empty list with the given capacity. // Precondition: capacity >= 0 public ArrayIntList(int capacity) { elementData = new int[capacity]; size = 0; } // Appends the given value to the end of the list. // Precondition: size < capacity (elementData.length) public void add(int value) { elementData[size] = value; size++; } // Inserts the given value at the given index, shifting subsequent values right. // Precondition: size < capacity && 0 <= index <= size() public void add(int index, int value) { for (int i = size; i > index; i--) { elementData[i] = elementData[i - 1]; } elementData[index] = value; size++; } // Returns the integer at the given index in the list. // Precondition: 0 <= index < size() public int get(int index) { return elementData[index]; } // Returns the position of the first occurence of the given value. // Returns a negative number if the value is not found. public int indexOf(int value) { for (int i = 0; i < size; i++) { if (elementData[i] == value) { return i; } } return -1; } // Removes the value at the given index, shifting subsequent values left. // Precondition: 0 <= index < size() public void remove(int index) { 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 a comma-separated, bracketed String representation of the list. 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; } } }