基于动态数组的泛型栈Push操作时数组越界问题求助
解决泛型动态栈的数组越界问题
你的代码核心问题出在初始传入长度为0的数组时,第一次扩容操作stackSize*2结果还是0,扩容后的数组长度依然为0,导致push时数组越界。此外还有几处细节逻辑需要调整,以下是具体修正方案:
1. 修复扩容的初始值逻辑
当栈初始大小为0时,不能直接翻倍,得设置一个最小扩容值(比如2),避免扩容后数组还是空的。修改incrementArray方法:
public void incrementArray() { int newSize = stackSize == 0 ? 2 : stackSize * 2; T[] temp = (T[]) new Object[newSize]; System.arraycopy(stack, 0, temp, 0, stack.length); stack = temp; stackSize = newSize; }
2. 修正缩容的条件与实现
原pop方法里的缩容条件判断有误,且缩容时可能把数组缩到0,需要调整:
- 先取出栈顶元素再修改
topStack,避免逻辑顺序错误 - 缩容条件改为当前元素个数≤容量的一半,同时保证缩容后容量不小于2
- 缩容时只复制当前存在的元素,而非整个原数组长度
修改后的pop和decrementArray方法:
public T pop() throws EmptyStackException { if (isEmpty()) { throw new EmptyStackException(); } T element = stack[topStack--]; int currentSize = topStack + 1; if (currentSize <= stackSize / 2 && stackSize > 2) { decrementArray(); } return element; } public void decrementArray() { stackSize = Math.max(stackSize / 2, 2); T[] temp = (T[]) new Object[stackSize]; System.arraycopy(stack, 0, temp, 0, topStack + 1); stack = temp; }
3. 补全缺失的导入
代码中使用了EmptyStackException,需要在开头添加导入语句:
import java.util.EmptyStackException;
4. 简化isEmpty和isFull方法
把冗余的if判断简化为一行代码,更简洁清晰:
public boolean isEmpty() { return topStack == -1; } public boolean isFull() { return topStack + 1 == stackSize; }
完整修正后的代码
import java.util.EmptyStackException; public class Stack<T> { private int topStack; private int stackSize; private T[] stack; // Constructor public Stack(T[] arr) { stack = arr; stackSize = arr.length; topStack = -1; } // 判断栈是否为空 public boolean isEmpty() { return topStack == -1; } // 判断栈是否已满 public boolean isFull() { return topStack + 1 == stackSize; } // 扩容数组,处理初始大小为0的情况 public void incrementArray() { int newSize = stackSize == 0 ? 2 : stackSize * 2; T[] temp = (T[]) new Object[newSize]; System.arraycopy(stack, 0, temp, 0, stack.length); stack = temp; stackSize = newSize; } // 缩容数组,确保最小容量为2 public void decrementArray() { stackSize = Math.max(stackSize / 2, 2); T[] temp = (T[]) new Object[stackSize]; System.arraycopy(stack, 0, temp, 0, topStack + 1); stack = temp; } // 入栈操作 public void push(T element) { if (isFull()) incrementArray(); topStack++; stack[topStack] = element; } // 查看栈顶元素 public T peek() { return stack[topStack]; } // 出栈操作 public T pop() throws EmptyStackException { if (isEmpty()) { throw new EmptyStackException(); } T element = stack[topStack--]; int currentSize = topStack + 1; if (currentSize <= stackSize / 2 && stackSize > 2) { decrementArray(); } return element; } public static void main(String[] args) { Stack<Integer> operands = new Stack<>(new Integer[0]); operands.push(2); operands.push(1); System.out.println(operands.peek()); // 输出1 operands.pop(); System.out.println(operands.peek()); // 输出2 } }
修正后的代码解决了初始空数组push时的越界问题,同时优化了动态扩容缩容的逻辑,保证栈能正常处理各种入栈出栈场景。
内容的提问来源于stack exchange,提问作者NinoCodes
相关产品推荐
相关产品推荐

