// Stuart Reges handout #27
// 3/7/05
//
// 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 size()
// returns the current number of elements in 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[] list; // array of integers
private int size; // 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");
this.list = new int[capacity];
this.size = 0;
}
// post: returns the current number of elements in the list
public int size() {
return this.size;
}
// pre : 0 <= index < length()
// post: returns the integer at the given index in the list
public int get(int index) {
checkIndex(index);
return this.list[index];
}
// pre : length() < capacity
// post: appends the given number to the end of the list
public void add(int number) {
if (this.size == this.list.length)
throw new IllegalStateException("list is full");
this.list[this.size] = number;
this.size++;
}
// pre : 0 <= index < length()
// post: removes the integer at the given index
public void remove(int index) {
checkIndex(index);
for (int i = index; i < this.size - 1; i++)
this.list[i] = this.list[i + 1];
this.size--;
}
// 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);
this.list[index] = value;
}
// post: list is empty
public void clear() {
this.size = 0;
}
// post: throws an exception if the given index is out of range
private void checkIndex(int index) {
if (index < 0 || index >= this.size)
throw new IndexOutOfBoundsException("illegal index");
}
}