繁体   English   中英

java 中的构造函数类型不匹配

[英]Constructor type mismatch in java

我在 java 自学链表,我正在编写一个基本程序。 我收到了与我无法理解的构造函数相关的错误。 这是我的代码:

import java.util.*;

public class prac{

public class Linked{

    public void display(Node head)
    {
        if(head==null) // list is empty
        {
            return ;
        }
        Node current=head;
        while(current!=null)
        {   System.out.print(current.data+ " --> ");
            current=current.next;
        }
        System.out.println(current);
    }
    private class Node{
        int data;
        Node next;
        public Node(int data)
        {
            this.data=data;
            this.next=null;
        }
    }
}
public static void main(String[] args)
{
    Node head=new Node(10);
    Node second=new Node(11);
    Node third=new Node(5);
    Node fourth=new Node(1);
    head.next=second;
    second.next=third;
    third.next=fourth;
    Linked linklist=new Linked();
    linklist.display(head);
}
}
Some of the errors are this:
error: constructor Node in class Node cannot be applied to given types;
    Node fourth=new Node(1);
                ^
  required: no arguments
  found: int
  reason: actual and formal argument lists differ in length
error: non-static variable this cannot be referenced from a static context
    Linked linklist=new Linked();
                    ^
prac.java:40: error: incompatible types: Node cannot be converted to prac.Linked.Node
    linklist.display(head);

谁能解释一下如何解决这个错误及其背后的原因? 我被困在这里。 /

如果你有一个内部 class 并且你有一个相同的变量类型,那么它将优先

  Node current=head;

这是指私有内部 class

在你的主要方法中

 Node head=new Node(10)

这是指不同的 class

要解决此问题,一个选项是更改内部 class 名称,另一个选项创建一个构造函数并将所有值复制到该 object

private class Node{
    int data;
    Node next;
    public Node(mypackage.Node node) {
        this.data = node.data;
        this.next = node.next;
    }

    public Node(int data)
    {
        this.data=data;
        this.next=null;
    }
}

然后将您显示的 function 更改为

Node current=new Node(head);

在此代码中mypackage假定为您自己的 package 或第三方库

您无法从更高的 scope 访问Node class,因为它对Linked的 class 是private的。 由于访问限制,只有在链接的 class 中,您才能实际创建节点 object。

在我的解决方案中,我最初拆分了类,因此Linked不再位于Prac class 内。 否则,由于Prac具有主要方法,您的所有方法都必须自然static

public static void main(String[] args)

此外,我选择将Node构造函数保持为私有,但公开一个您可以调用的addNode(int value)方法。

解决方案可以提供帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM