利用JAVA 实现堆栈,出现编译错误,请高人知道.谢谢
// public class arrayStack{
class ArrayStack<E>{
protected int capacity;
protected E S[];
protected int top = -1;
public static final int CAPACITY=10;
public ArrayStack() {
this(CAPACITY); // default capacity
}
public ArrayStack(int cap){
capacity = cap;
S= (E[]) new Integer[capacity];
}
public void push(E element) {
S[++top] = element;
}
public E pop(){
E element;
element = S[top];
S[top--]= null;
return element;
}
}
public class arrayStack{
public static void main(String[] args){
ArrayStack<Integer> Stack = new ArrayStack<Integer>();
Stack.capacity = 6;
Stack.push(4);
Stack.push(1);
Stack.push(3);
while(Stack.top>=0)
Stack.pop();
Stack.push(8);
while(Stack.top>=0)
Stack.pop();
};
}
报错:无法在调用超类型构造器之前引用CAPACITY
this<CAPACITY>;//default capacity
--------------------编程问答--------------------
class ArrayStack<E> {
protected int capacity;
protected E S[];
protected int top = -1;
public static final int CAPACITY = 10;
public ArrayStack() {
this(CAPACITY); // default capacity
}
public ArrayStack(int cap) {
capacity = cap;
S = (E[]) new Integer[capacity];
}
public void push(E element) {
S[++top] = element;
}
public E pop() {
E element;
element = S[top];
S[top--] = null;
return element;
}
}
public class ArrayStackTest {
public static void main(String[] args) {
ArrayStack<Integer> Stack = new ArrayStack<Integer>();
Stack.capacity = 6;
Stack.push(4);
Stack.push(1);
Stack.push(3);
while (Stack.top >= 0)
System.out.println(Stack.pop());
Stack.push(8);
while (Stack.top >= 0)
System.out.println(Stack.pop());
};
}
你定义的类名真让人蛋疼 ,我只改了 arrayStack -->ArrayStackTest 就可以了 --------------------编程问答-------------------- 结果:
3
1
4
8
补充:Java , Java EE