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

如何修复Java代码中出现的找不到符号(cannot find symbol)错误?

解决Java代码中"cannot find symbol: method size()"错误

首先,咱们来定位问题:报错的super.size()找不到符号,核心原因是你继承的自定义LinkedList类(注意不是Java标准库的java.util.LinkedList,因为你用了addToTail、removeFromHead这类非标准方法)没有提供size()方法。

下面给你几个可行的解决方案:

方案1:给自定义LinkedList添加size()方法

这是最合理的方式,咱们在自定义的LinkedList类里维护一个size变量,在添加、删除元素时同步更新它,再提供size()方法:

// 假设这是你的自定义LinkedList类
class LinkedList {
    private Node head;
    private Node tail;
    private int size = 0; // 新增size变量

    // 示例:addToTail方法中更新size
    public void addToTail(Object item) {
        Node newNode = new Node(item);
        if (tail == null) {
            head = newNode;
            tail = newNode;
        } else {
            tail.next = newNode;
            tail = newNode;
        }
        size++; // 添加后size+1
    }

    // 示例:removeFromHead方法中更新size
    public Object removeFromHead() {
        if (head == null) return null;
        Object data = head.data;
        head = head.next;
        if (head == null) tail = null;
        if (size > 0) size--; // 删除后size-1
        return data;
    }

    // 新增size()方法
    public int size() {
        return size;
    }

    // 你的其他LinkedList方法(比如isEmpty)
    public boolean isEmpty() {
        return head == null;
    }

    // 内部Node类
    private class Node {
        Object data;
        Node next;
        Node(Object data) {
            this.data = data;
        }
    }
}

这样你的ListQueue里的super.size()就能正常调用了。

方案2:在ListQueue的size()方法中自行实现计数

如果暂时不想修改自定义LinkedList,也可以在ListQueue里直接遍历链表统计元素个数(但效率较低,不推荐频繁调用):

public class ListQueue extends LinkedList { 
    public ListQueue() { super(); } 
    public boolean empty() { return isEmpty(); } 
    public void enqueue(Object item) { addToTail(item); } 
    public Object dequeue() { return removeFromHead(); } 
    public int size(){ 
        int count = 0;
        // 假设自定义LinkedList有head节点的访问权限,或者提供getHead()方法
        Node current = head; 
        while (current != null) {
            count++;
            current = current.next;
        }
        return count;
    } 
}

方案3:改用Java标准库的LinkedList

如果你不需要自定义LinkedList的特殊逻辑,直接用Java自带的java.util.LinkedList会更省心,它自带size()、isEmpty()、addLast()、removeFirst()这些方法,代码可以改成:

import java.util.LinkedList;

public class ListQueue extends LinkedList<Object> { 
    public ListQueue() { super(); } 
    public boolean empty() { return isEmpty(); } 
    public void enqueue(Object item) { addLast(item); } // 替代addToTail
    public Object dequeue() { return removeFirst(); } // 替代removeFromHead
    public int size(){ return super.size(); } // 现在不会报错了
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:19:27