【问题标题】:The method getCount is undefined for type LinkedList类型 LinkedList 的方法 getCount 未定义
【发布时间】:2016-06-21 05:57:05
【问题描述】:

我正在尝试获取列表的计数。我编写了单独的函数来获取计数。当我将其调用为主时,它会引发错误。 错误是

类型 LinkedList 的 getCount 未定义。

我的代码是

import java.util.*;
import java.util.LinkedList.*;
public class LengthCount {
Node head;
// Insert a new node from the front.
public void push(int new_data){
    Node new_node = new Node(new_data);
    new_node.next = head;
    head = new_node;
}
// Function for getting count
public int getCount(){
    int count = 0;
    Node temp = head;
    while(temp != null){
        count++;
        temp = temp.next;
    }
    return count;
}
public static void main(String[] args) {
    LinkedList llist = new LinkedList();
    llist.push(1);
    llist.push(3);
    llist.push(1);
    llist.push(2);
    llist.push(1);
    System.out.println("Counts of node is : "+llist.getCount()); // Error in this line

}

}

谁能帮帮我

【问题讨论】:

  • 您在 LengthCount 类中定义了该方法。为什么你希望它出现在 java.util.LinkedList 中?
  • LinkedList 没有成员函数 getCount() (API)。
  • getcount 是用户定义函数。我们可以用列表调用用户定义函数吗?谢谢!!

标签: java list data-structures


【解决方案1】:

GetCount 是在 LengthCount 类中定义的方法。因此,您必须要么创建类的对象来访问该方法,要么使用 this.getCount()

你不能使用 List.getCount() 因为链表类没有那个方法,它有 List.size();

【讨论】:

  • 那么就不需要为push和get count写不同的函数了。我们可以直接从 API 使用吗?
  • 是的,API 方法产生最佳结果。此外,如果您必须更改任何实现,则继承基列表类并覆盖其功能。
  • 感谢 Sthya。这将有助于更多地理解链表
【解决方案2】:

我猜你想得到列表的长度。然后使用 API。这是您修改后的代码

import java.util.*;


public class LengthCount {

    public static void main(String[] args) {
        LinkedList llist = new LinkedList();
        llist.push(1);
        llist.push(3);
        llist.push(1);
        llist.push(2);
        llist.push(1);
        System.out.println("Counts of node is : "+llist.size());

    }}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-23
    • 2016-06-07
    • 2021-06-19
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多