首页 > 解决方案 > 如何在运行时传递数组的大小?

问题描述

我认为下面的代码片段可能会运行。

public class Stack {
    int n;
    char arr[]=new char[n];
    int top=0;

    void Push(char val) {
        arr[top]=val;
        top++;   
    }
}

class Solution {
    public static void main(String[] args) {
        Stack obj=new Stack();
        obj.n=5;
        obj.Push('a');
        obj.Push('a');
        obj.Push('a');
        obj.Push('a');
    }
}

但是它给出了一个ArrayOutOfBoundsException. 为什么数组的大小没有变为 5?

标签: javaarraysdata-structures

解决方案


为您的堆栈使用构造函数。默认n值设置为零。因此,您的数组正在以 0 大小创建。像下面这样的参数化构造函数应该为您完成这项工作。

      public class Stack {
        int n;
        char arr[];
        int top=0;

        public Stack(int n) {
            this.n = n;
            this.arr = new char[n];
        }

    }

推荐阅读