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

Java自定义Queue实现运行时peek()方法报数组下标越界异常如何解决

问题分析与修复方案

错误原因

  • 队列初始化时frontIndex被赋值为-1,但enqueue入队方法仅更新了backIndex的取值,没有在队列首次插入元素时同步修改frontIndex的值,调用peek()方法时直接用值为-1的frontIndex访问数组元素,触发数组下标越界异常。
  • 现有代码还缺少isFull()方法的实现,会先触发编译错误。

修复步骤

  1. 补全isFull()方法,判断队列是否已满的逻辑为backIndex == size - 1
  2. 修改enqueue方法,首次插入元素时将frontIndex设置为0
  3. 可选优化:给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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 22:06:02