/**
* The ExpandableArray class allows a user to add and remove
* integers to/from the end of an array with an initial size of 4
* which doubles in size when full
*
* @author Suzanne Balik, 10 Apr 2002
*/
public class ExpandableArray {
final int INITIAL_SIZE = 4;
int numberOfValues;
int [] values;
public ExpandableArray() {
numberOfValues = 0;
values = new int[INITIAL_SIZE];
}
public void addNumber(int number) {
if (numberOfValues == values.length)
expand();
values[numberOfValues] = number;
numberOfValues++;
}
private void expand() {
int[] temp = new int[values.length * 2];
for (int i = 0; i < numberOfValues; i++)
temp[i] = values[i];
values = temp;
}
public void removeLastNumber() {
if (numberOfValues > 0)
numberOfValues--;
}
public String toString() {
String s = "";
for (int i = 0; i < numberOfValues; i++) {
s += values[i] + " ";
if (i % 8 == 7)
s += "\n";
}
return s;
}
public static void main(String[] args) {
ExpandableArray myArray = new ExpandableArray();
final int MAX = 10;
for (int i = 0; i < MAX; i++) {
myArray.addNumber(2);
myArray.addNumber(4);
myArray.addNumber(6);
myArray.addNumber(3);
System.out.println("LIST");
System.out.println(myArray);
}
}
}