import java.util.*;
/**
* BasicArrayList.java
* Illustrates the implementation of several of the ArrayList methods.
*
* Created: Wed Feb 19 11:24:05 2003
*
* @author Stuart C. Shapiro
* Documentation from Java API
*/
public class BasicArrayList extends AbstractList {
private Object[] array;
private int capacity;
private int currentSize;
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list.
* @exception IllegalArgumentException
* if the specified initial capacity is negative
*/
public BasicArrayList (int initialCapacity) throws IllegalArgumentException {
super();
if (initialCapacity < 0) {
throw new IllegalArgumentException();
}
capacity = initialCapacity;
array = new Object[capacity];
currentSize = 0;
}
/**
* Constructs an empty list with an initial capacity of ten.
*
*/
public BasicArrayList (){
this(10);
}
/**
* Returns the element at the specified position in this list.
*
* @param index index of element to return.
* @return the element at the specified position in this list.
* @exception IndexOutOfBoundsException if index out of range
* (index < 0 || index >= size()).
*/
public Object get(int index) throws IndexOutOfBoundsException {
if (index < 0 || index >= currentSize) {
throw new IndexOutOfBoundsException();
}
return array[index];
}
/**
* Returns the number of elements in this list.
*
* @return the number of elements in this list.
*/
public int size() {
return currentSize;
}
/**
* Appends the specified element to the end of this list.
*
* @param o element to be appended to this list.
* @return true (as per the general contract of Collection.add).
*/
public boolean add(Object o) {
if (currentSize == capacity) {
Object[] oldarray = array;
capacity *= 2;
array = new Object[capacity];
for (int i = 0; i < currentSize; i++) {
array[i] = oldarray[i];
} // end of for (int i = 0; i < currentSize-1; i++)
} // end of if (currentSize == capacity)
array[currentSize++] = o;
return true;
}
/**
* Removes the element at the specified position in this
* list. Shifts any subsequent elements to the left (subtracts one
* from their indices).
*
* @param index the index of the element to removed.
* @return the element that was removed from the list.
* @exception IndexOutOfBoundsException if index out of range
* (index < 0 || index >= size()).
*/
public Object remove(int index) throws IndexOutOfBoundsException {
if (index < 0 || index >= currentSize) {
throw new IndexOutOfBoundsException();
}
Object result = array[index];
for (int i = index; i < currentSize-1; i++) {
array[i] = array[i+1];
} // end of for (int i = index; i < currentSize-1; i++)
currentSize--;
return result;
}
/**
* Returns a string representation of this list.
*
* @return a string representation of this list.
*/
public String toString() {
String result = "[";
for (int i = 0; i < currentSize-1; i++)
result += array[i] + ", ";
if (currentSize > 0) {
result += array[currentSize-1];
}
return result + "]";
}
}// BasicArrayList