将数组从构造函数传递给方法?

时间:2015-10-28 16:27:01

标签: java

当我尝试运行它时,我得到了:线程中的异常" main" java.lang.ArrayIndexOutOfBoundsException:0 我想在构造函数SimpleIntegerStack中初始化数组,稍后在后面的方法中使用它...

package datastructures.simple_integer_stack;

public class SimpleIntegerStack {
int maxSize;
private int stack[]=new int[maxSize];

public SimpleIntegerStack(int maxSize) {

    int stack[]= new int [maxSize];
}

public void push(int element) {
    int i=-1;
    boolean stop = false;

    do{
        if(stack[i]==0){
            stack[i]=element;
            stop=true;
        }
        i++;

    }while(stop=false && i<stack.length);

}

public void pop() {
    int i=0;

    while(stack[i]!=0 && i<stack.length){
        i++;
    }
    if(i!=0)
        stack[i] = 0;
}

public int top() {
    int stacktop=-1;
    int i=0;
    boolean empty = true;
    while(stack[i]!=0 && i<stack.length-1){
        i++;
        empty=false;
    }
    if(i==stack.length-1){
        if (stack[i+1]==0){
            empty=true;
        }
        else stacktop=stack[i+1];
    }
    if(empty=false)
        stacktop=stack[i-1];
    return stacktop;
}

}

1 个答案:

答案 0 :(得分:1)

从以下代码中删除“int”:

public SimpleIntegerStack(int maxSize) {

    // dont do this:  int stack[]= new int [maxSize];
    stack = new int[maxSize];  
}

您所做的是在构造函数中声明局部变量stack。此变量恰好与实例变量具有相同的名称。当构造函数完成时,局部变量超出范围。

因此,实例变量stack不受对构造函数的调用的影响。