栈为空时调用push却抛出‘Stack is full’异常的问题排查
十进制转二进制时ArrayStack抛出栈满异常
实现的代码
泛型栈类ArrayStack
基于数组实现的泛型栈ArrayStack<E>,包含基础栈操作方法,关键代码如下:
// 构造方法:指定栈容量 public ArrayStack(int capacity) { arr = (E[]) new Object[capacity]; } // 栈顶指针(初始为-1,表示空栈) private int t = -1; // 返回栈中元素数量 public int size() { return t + 1; } // 压栈方法:栈满时抛出异常 public void push(E element) throws IllegalStateException { if (size() == arr.length) { throw new IllegalStateException("Stack is full"); } arr[++t] = element; }
十进制转二进制类dec_to_bin
该类创建容量为32的ArrayStack<Long>实例,用于存储二进制位:
ArrayStack<Long> a1 = new ArrayStack<Long>(32);
负责进制转换与压栈的pushing()方法代码:
public void pushing(long num) { while (num > 0) { long remainder = num % 2; a1.push(remainder); num = num / 2; } // 处理输入为0的情况 if (num == 0) { a1.push(0L); } }
抛出的异常信息
执行压栈操作时触发栈满异常:
Exception in thread "main" java.lang.IllegalStateException: Stack is full at ArrayStack.push(test.java:36) at dec_to_bin.pushing(test.java:64) at dec_to_bin.process(test.java:75) at test.main(test.java:115)
问题分析与修复方案
核心原因
栈容量固定为32,但实际压入的二进制位数超过32位,常见触发场景:
- 输入数值超出32位无符号整数范围:比如输入
4294967296(即2^32),其二进制为1后接32个0,共33位,压栈时超出容量。 pushing()方法逻辑冗余:当输入为0时,循环不执行但会额外压入一个0;如果输入的数值转换后刚好32位,加上这个额外的0就会触发栈满。
修复方案
方案1:修正pushing()方法逻辑
移除冗余的0压入操作,仅当栈为空且输入为0时才压入0:
public void pushing(long num) { // 仅当输入为0且栈为空时压入0,避免冗余 if (num == 0) { if (a1.isEmpty()) { a1.push(0L); } return; } // 正数转二进制逻辑 while (num > 0) { long remainder = num % 2; a1.push(remainder); num = num / 2; } }
方案2:扩容栈容量
若需支持更大数值(如64位整数),直接将栈容量设为64:
ArrayStack<Long> a1 = new ArrayStack<Long>(64);
方案3:实现栈自动扩容
修改ArrayStack的push()方法,当栈满时自动扩容为原容量的2倍,彻底摆脱固定容量限制:
import java.util.Arrays; // 修改后的push方法 public void push(E element) { if (size() == arr.length) { // 自动扩容为原容量的2倍 arr = Arrays.copyOf(arr, arr.length * 2); } arr[++t] = element; }
内容的提问来源于stack exchange,提问作者Bruhbytes
相关产品推荐
相关产品推荐

