// Stuart Reges handout #31
// 12/6/04
//
// Class IntList can be used to store a list of integers. It has several
// methods that involve indexing the list. As with Java arrays and Strings,
// index values start with 0. Class IntList has the following public methods:
//
// public IntList()
// constructs an integer list of default capacity
// public IntList(int capacity)
// constructs an integer list with given capacity
//
// public int length()
// returns the current length of the list
// public int get(int index)
// returns the integer at the given index
//
// public void add(int number)
// appends the given number to the end of the list
// public void remove(int index)
// removes the value at the given index, shifting subsequent elements left
// public void set(int index, int number)
// replaces the value at the given index with the given value
// public void clear()
// removes all elements from the list making it empty
public class IntList {
private int[] myList; // array of integers
private int myLength; // current length of list
public static final int DEFAULT_CAPACITY = 100;
// post: constructs an empty integer list of default capacity
public IntList() {
this(DEFAULT_CAPACITY);
}
// pre : capacity >= 0
// post: constructs an empty integer list with the given capacity
public IntList(int capacity) {
if (capacity < 0)
throw new IllegalArgumentException("negative capacity");
myList = new int[capacity];
myLength = 0;
}
// post: returns the current length of the list
public int length() {
return myLength;
}
// pre : 0 <= index < length()
// post: returns the integer at the given index in the list
public int get(int index) {
checkIndex(index);
return myList[index];
}
// pre : length() < capacity
// post: appends the given number to the end of the list
public void add(int number) {
if (myLength == myList.length)
throw new IllegalStateException("list is full");
myList[myLength] = number;
myLength++;
}
// pre : 0 <= index < length()
// post: removes the integer at the given index
public void remove(int index) {
checkIndex(index);
for (int i = index; i < myLength - 1; i++)
myList[i] = myList[i + 1];
myLength--;
}
// pre : 0 <= index < length()
// post: replaces the integer at the given index with the given value
public void set(int index, int value) {
checkIndex(index);
myList[index] = value;
}
// post: list is empty
public void clear() {
myLength = 0;
}
// post: throws an exception if the given index is out of range
private void checkIndex(int index) {
if (index < 0 || index >= myLength)
throw new IndexOutOfBoundsException("illegal index");
}
}