尝试将一些数据结构用java实现,尝试过程中确实碰到一些问题,收获很大import java.lang.reflect.Array;
class ArrayStack {
Class type;
private T[] values;
private int maxSize;
private int top;
public ArrayStack(Class type, int maxSize) {
this.type = type;
this.maxSize = maxSize;
//values = new T[maxSize];
values = (T[])Array.newInstance(type, maxSize);
top = -1;
}
public T pop() {
if(top == -1)
return null;
return values[top--];
}
public void push(T value) {
if(top == maxSize-1)
return;
values[++top] = value;
}
}
public class Test {
public static void main(String[] args) {
ArrayStack stack = new ArrayStack(Integer.class, 10);
for(int i=0; i<10; i++) {
stack.push(Integer.valueOf(i));
}
for(int i=0; i<10; i++) {
System.out.println(stack.pop());
}
ArrayStack stackOfChars = new ArrayStack(Character.class, 10);
for(int i=0; i<10; i++) {
stackOfChars.push((char)(i+65));
}
for(int i=0; i<10; i++) {
System.out.println(stackOfChars.pop());
}
}
}