Java自定义Queue实现运行时peek()方法报数组下标越界异常如何解决
问题分析与修复方案
错误原因
- 队列初始化时
frontIndex被赋值为-1,但enqueue入队方法仅更新了backIndex的取值,没有在队列首次插入元素时同步修改frontIndex的值,调用peek()方法时直接用值为-1的frontIndex访问数组元素,触发数组下标越界异常。 - 现有代码还缺少
isFull()方法的实现,会先触发编译错误。
修复步骤
- 补全
isFull()方法,判断队列是否已满的逻辑为backIndex == size - 1 - 修改
enqueue方法,首次插入元素时将frontIndex设置为0 - 可选优化:给
peek()方法增加空队列判断,避免空队列调用时抛出异常
修复后完整代码
public class Queue { int size; int frontIndex; int backIndex; int arr[]; Queue() { size = 5; frontIndex = -1; backIndex = -1; arr = new int[size]; } // 补全isFull方法 public boolean isFull() { return backIndex == size - 1; } // 新增空队列判断方法 public boolean isEmpty() { return frontIndex == -1 || frontIndex > backIndex; } public int peek() { if (isEmpty()) { throw new RuntimeException("Queue is empty"); } return arr[frontIndex]; } public void enqueue(int data) { if (isFull()) { System.out.println("Queue is overflow"); } else { // 首次插入元素时修改frontIndex if (frontIndex == -1) { frontIndex = 0; } System.out.println("Insert " + data); backIndex++; arr[backIndex] = data; } } public static void main(String[] args) { Queue queue = new Queue(); queue.enqueue(15); queue.enqueue(18); System.out.println("Front element of queue is " + queue.peek()); } }
运行结果
修复后代码运行输出如下:
Insert 15 Insert 18 Front element of queue is 15
内容的提问来源于stack exchange,提问作者user14364844
相关产品推荐
相关产品推荐

