import structure5.*;
/**
Dynamic array (like java.util.ArrayList)
(Partial implementation)
Morgan McGuire
morgan@cs.williams.edu
*/
public class Array {
/**
Space reserved for storage. Never null.
Values > count are null.
*/
protected Value[] data;
/** Number of elements of data that are actually visible to the
* user. */
protected int count;
public Array() {
data = allocateArray(0);
count = 0;
}
/** Number of elements stored in the Array. */
public int size() {
return count;
}
/** Return the element at i */
public Value get(int i) {
Assert.pre(i < count && i >= 0, "Index out of bounds: i = " + i);
return data[i];
}
/** Set element i to value v */
public void set(int i, Value v) {
Assert.pre(i < count && i >= 0, "Index out of bounds: i = " + i);
data[i] = v;
}
/** Adds to the end of the array. */
public void add(Value v) {
setSize(count + 1);
data[count] = v;
}
/**
Java can't allocate an array of a type parameter, so this
method implements new Value[N] for us as a trick of casting
from Object[]. This works only because Java arrays have
(compared to most languages) bizarre subclass behavior;
e.g., array SET is covariant instead of contravariant.
*/
// The cast from Object[] to Value[] will generate a warning
@SuppressWarnings( "unchecked" )
private Value[] allocateArray(int N) {
return (Value[])(new Object[N]);
}
/**
Newly exposed elements are null.
*/
public void setSize(int N) {
// ???? Coming next time...
}
}