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

问题描述 投票:0回答:1

我是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);

任何人都可以解释如何解决此错误及其原因吗?我被困在这里。/

java class constructor linked-list singly-linked-list
1个回答
0
投票

如果您有一个内部类,并且具有相同的变量类型,则将具有优先级

  Node current=head;

这是指内部私有类

在您的主要方法中

 Node head=new Node(10)

这是指另一个类

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

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

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

然后将您的功能更改为

Node current=new Node(head);
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.