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
MAXvariable: You markedMAXasstatic, which means it’s shared across all instances of yourstackclass. Worse, staticintvariables default to 0 when the class loads. So when yourmy_stackarray is initialized (before the constructor runs), it becomesnew int[0]—an empty array. By the time your constructor setsMAXto the desired size, the array is already stuck as length 0, so anypushcall tries to access an index in an empty array, triggering the error. - Timing of array initialization: In Java, member variables like
my_stackare initialized before the constructor executes. SinceMAXis 0 at that point, your array ends up empty no matter what value you assign toMAXlater.
Additional Small Bugs to Fix
While we’re at it, there are a couple of other minor issues in your code:
- The
pushoverflow check usesif (this.top > MAX)—this is wrong. Yourtopstarts at 0, and the last valid index of the array isMAX-1. You should check iftop >= MAXto detect when the stack is full. - The
top()method doesn’t handle empty stacks. If you call it whentopis 0, you’ll try to accessmy_stack[-1], which throws another error. - Using
staticforMAXmeans 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
- Removed
staticfromMAX: Each stack instance now has its own independent maximum capacity. - Moved array initialization to constructors: Ensures we create the array with the correct size only after
MAXis set. - Fixed the overflow check in
push: Now correctly identifies when the stack is full. - Added safety check in
top(): Prevents invalid index access when the stack is empty. - 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
相关产品推荐
相关产品推荐

