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

实现MyList接口的MyFixedSizeArrayList类无法调用方法问题求助

问题原因及修复方案

核心错误(直接导致方法无法调用)

  • 你调用方法的对象类型完全错误:你将自定义的MyFixedSizeArrayList实例作为元素存入了JDK自带的java.util.List集合中,用List<?>类型的变量fixedArraySize直接调用insert方法,而JDK的List接口根本没有定义你自己写的insert方法,自然无法访问。
  • 你混淆了集合和元素的关系:Arrays.asList(new MyFixedSizeArrayList(5))返回的是一个存放了MyFixedSizeArrayList对象的JDK List集合,不是你的自定义List实例本身。

其他潜在问题

  • 泛型实现不规范:MyList是带泛型参数的接口MyList<E>,你实现的时候直接写implements MyList使用了原生类型,会导致类型不安全的警告。
  • 构造方法逻辑缺失:你在MyFixedSizeArrayList的构造方法中接收了arraySize参数,但没有给类的同名成员变量赋值,后续调用getSize()方法时会抛出空指针异常。
  • insert方法逻辑不合理:你在insert方法内部又定义了Scanner读取用户输入,直接覆盖了传入的data参数,方法参数完全没有起到作用。

修复示例

第一步:修正MyFixedSizeArrayList的实现

public class MyFixedSizeArrayList<E> implements MyList<E> {
    private int maxSize;
    private Object[] elements;
    private int currentSize = 0;

    public MyFixedSizeArrayList(int maxSize) {
        // 给成员变量赋值
        this.maxSize = maxSize;
        this.elements = new Object[maxSize];
    }

    @Override
    public int getSize() {
        return currentSize;
    }

    @Override
    public void insert(E data) throws ListOverflowException {
        if (currentSize >= maxSize) {
            throw new ListOverflowException("列表已满");
        }
        elements[currentSize++] = data;
        System.out.println("The " + data + " has been stored");
    }

    // 剩下的getElement、delete、search方法按需求补全即可
}

第二步:修正main方法的调用逻辑

public static void main(String[]args) throws ListOverflowException {
    Scanner keyboard = new Scanner(System.in);
    // 直接声明为你自己的MyList类型,创建自定义类的实例
    MyList<String> myList = new MyFixedSizeArrayList<>(5);
    System.out.print("Input the data that you want to store: ");
    String data = keyboard.next();
    // 调用自定义的insert方法
    myList.insert(data);
}

内容的提问来源于stack exchange,提问作者Julliard - Kun

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:36:04