// CSE 143, Winter 2009, Marty Stepp // An ArrayIntList object stores an ordered list of integers using // an unfilled array. // This version of the class adds new methods: remove, indexOf, toString. // It also adds a second constructor with a capacity parameter. // // Please DO NOT use this version of the file for your homework assignment. // Use the one located on the Homework section of the course web site. public class ArrayIntList { // data (fields) // They are 'protected' to allow subclasses to access them. protected int[] elementData; // stores the list's elements protected int size; // number of elements in the list // constructors (creates/initializes new objects) // Initializes a new empty list that can hold up to 1000 integers. public ArrayIntList() { this(1000); } // Initializes a new empty list that can hold up to the given number of integers. public ArrayIntList(int capacity) { elementData = new int[capacity]; size = 0; } // behavior (methods) // Adds the given value to the end of the list. // Precondition: size < elementData.length public void add(int value) { elementData[size] = value; size++; } // Inserts the given value into the list at the given index, // sliding subsequent elements right to make room for it. // Precondition: size < elementData.length and 0 <= index <= size public void add(int index, int value) { // shift elements right to make room for the new element for (int i = size; i > index; i--) { elementData[i] = elementData[i - 1]; } elementData[index] = value; size++; } // Returns the value in the list at the given index. // Precondition: 0 <= index < size public int get(int index) { return elementData[index]; } // Sets the given index to store the given value. // Precondition: 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; } // Removes the element from the given index from this list, // sliding subsequent elements left to fill the gap created. // Precondition: 0 <= index < size public void remove(int index) { for (int i = index; i < size - 1; i++) { elementData[i] = elementData[i + 1]; } size--; elementData[size] = 0; // optional } // Returns the first index at which the given value is found in this list. // If the value is not found, returns -1. public int indexOf(int value) { for (int i = 0; i < size; i++) { if (elementData[i] == value) { return i; } } return -1; // not found } // Returns a String representation of this list, such as "[10, -3, 42, 9]". public String toString() { if (size == 0) { return "[]"; } else { // fencepost problem String result = "[" + elementData[0]; for (int i = 1; i < size; i++) { result += ", " + elementData[i]; } result += "]"; return result; } } }