You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java新手(具备C++经验)实现栈类时遭遇Index 0 out of bounds错误求助

Fixing the Index Out-of-Bounds Error in Your Custom Java Stack

Hey there! Let's break down why you're hitting that Index 0 out of bounds for length 0 error and fix your stack class step by step.

The Root Cause: Initialization Order & Static Variable Misuse

Your error comes down to two critical issues:

  • Static MAX variable: You marked MAX as static, which means it’s shared across all instances of your stack class. Worse, static int variables default to 0 when the class loads. So when your my_stack array is initialized (before the constructor runs), it becomes new int[0]—an empty array. By the time your constructor sets MAX to the desired size, the array is already stuck as length 0, so any push call tries to access an index in an empty array, triggering the error.
  • Timing of array initialization: In Java, member variables like my_stack are initialized before the constructor executes. Since MAX is 0 at that point, your array ends up empty no matter what value you assign to MAX later.

Additional Small Bugs to Fix

While we’re at it, there are a couple of other minor issues in your code:

  • The push overflow check uses if (this.top > MAX)—this is wrong. Your top starts at 0, and the last valid index of the array is MAX-1. You should check if top >= MAX to detect when the stack is full.
  • The top() method doesn’t handle empty stacks. If you call it when top is 0, you’ll try to access my_stack[-1], which throws another error.
  • Using static for MAX means all stack instances share the same maximum size—this is almost certainly not what you want (e.g., creating a stack with size 5 and another with size 10 would overwrite the first’s max capacity).

Corrected Code

Here’s the fixed version of your stack class, with comments explaining each change:

public class Stack { // Renamed to follow Java's PascalCase class naming convention
    private int MAX; // Removed static—each stack instance gets its own max size
    private int[] my_stack; // Declare array here, initialize in constructor
    private int top = 0;

    Stack(int a) {
        MAX = a;
        my_stack = new int[MAX]; // Initialize array AFTER setting MAX to the correct value
    }

    Stack() {
        MAX = 1000;
        my_stack = new int[MAX]; // Initialize default-sized array
    }

    public void push(int x) {
        if (this.top >= MAX) { // Fixed overflow check to catch full stack
            System.out.println("OVERFLOW");
        } else {
            my_stack[this.top++] = x;
        }
    }

    public void pop() {
        if (this.top == 0) {
            System.out.println("TOO LOW");
        } else {
            this.top--;
        }
    }

    public int top() {
        if (this.top == 0) {
            throw new IllegalStateException("Stack is empty"); // Add safety check for empty stack
        }
        return my_stack[this.top - 1];
    }
}

Key Changes Recap

  1. Removed static from MAX: Each stack instance now has its own independent maximum capacity.
  2. Moved array initialization to constructors: Ensures we create the array with the correct size only after MAX is set.
  3. Fixed the overflow check in push: Now correctly identifies when the stack is full.
  4. Added safety check in top(): Prevents invalid index access when the stack is empty.
  5. Renamed class to Stack: Followed Java’s standard naming conventions for better readability.

Give this a go—your out-of-bounds error should disappear, and the stack will work as expected!

内容的提问来源于stack exchange,提问作者Cosmin Andrei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 13:52:44