ArrayStore.java
public abstract class ArrayStore implements STORE {
Object[] array = new Object[10];
int length = 0;
public boolean isEmpty() {
return length == 0;
}
protected void growTo(int newsize) {
// Assume newsize > length
if(newsize > array.length) {
int growsize = Math.max(array.length*2,1);
while (newsize > growsize) {growsize = 2*growsize;};
Object[] newArray = new Object[growsize];
for (int i = 0; i < length; i++) {
newArray[i] = array[i];
};
array = newArray;
};
}
protected void shrinkTo(int newsize) {
// Assume newsize <= length
if(newsize <= array.length/2) {
int shrinksize = array.length/2;
while (newsize <= shrinksize/2 & shrinksize >= 2) {
shrinksize = shrinksize/2;
};
Object[] newArray = new Object[shrinksize];
for (int i = 0; i < length; i++) {
newArray[i] = array[i];
};
array = newArray;
};
}
public void add(Object o) {
int ol = length;
growTo(length+1);
length++;
array[ol] = o;
}
public void addAll(Object[] a) {
for(int i = 0; i < a.length; i++) {
add(a[i]);
}
}
public Object remove() {
if (isEmpty()) {length = 0; return null;};
Object o = array[--length];
shrinkTo(length);
return o;
}
public int size() {
return length;
}
public void execute(FUNCTION f) {
if (isEmpty()) return;
for (int i = 0; i < length; i++) {
f.value(array[i]);
};
}
public STORE map(FUNCTION f) {
MapFunction mf = null;
try {mf = new MapFunction((STORE)this.getClass().newInstance(),f);}
catch (Exception e) {throw new InternalError(e.getMessage());}
execute(mf);
return mf.store();
}
}
class MapFunction implements FUNCTION {
STORE store;
FUNCTION f;
MapFunction(STORE s, FUNCTION f) {
store = s;
this.f = f;
};
public Object value(Object o) {
store.add(f.value(o));
return null;
}
STORE store() {
return store;
}
}
On to Stack.java Part of store
Hubert BaumeisterJune 21, 1997
Imprint | Data Protection