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

PersonQueue未重写Queue接口addLast()方法报错问题求助

解决PersonQueue未重写Queue抽象方法的问题

嘿,这个问题其实是泛型使用不当导致的,我来给你拆解清楚:

问题根源

你定义的Queue是一个泛型接口Queue<T>,但在实现它的时候,PersonQueue用了原始类型Queue(没有指定泛型参数)。Java在处理原始类型时会触发类型擦除,把接口里的addLast(T o)转换成addLast(Object o)。而你写的addLast(Person person)是一个重载方法,并不是对接口方法的重写,所以编译器会认为你没有实现接口要求的addLast(Object)方法,就抛出了那个报错。

修复步骤

  1. 指定泛型参数:让PersonQueue明确实现Queue<Person>,这样接口的泛型T就会被替换成Person,和你类里的方法参数匹配。
  2. 添加@Override注解:这个注解能让编译器帮你校验是否正确重写了接口方法,避免后续再踩类似的坑。

修正后的完整代码

public interface Queue<T> {
    void addLast(T o) throws IllegalStateException;
}

public class PersonQueue implements Queue<Person> {
    private Person[] queue = new Person[1000];
    private int curIndex = 0;

    @Override
    public void addLast(Person person) throws IllegalStateException {
        if (curIndex < queue.length) { // 顺便提一句,你原来的判断条件写反啦,应该是curIndex小于队列长度才可以添加
            queue[curIndex] = person;
            curIndex++;
        } else {
            throw new IllegalStateException("Queue is already full");
        }
    }
}

另外,我还注意到你原来的判断条件queue.length > curIndex逻辑有误,当curIndex等于队列长度时,这个条件会不成立,刚好是队列满的情况,但初始化时curIndex为0,队列长度1000,条件成立没问题,不过正确的逻辑应该是判断curIndex < queue.length,这样语义更清晰,也避免逻辑歧义~

内容的提问来源于stack exchange,提问作者Lea

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:04:46