繁体   English   中英

内部类vs静态内部类

[英]Inner Class vs Static Inner Class

我正在尝试使用内部类创建链接列表实现

package linkedlist;

public class linkedList {

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

    public Node addToHead(int data)
    {
        Node node = new Node(data);
        Node current = this;
        node.next=current;
        return node;
    }
}

public static void findn(Node head)
{
    Node previous=head;
    Node current = head;
    int i =1;
    while(current!=null)
    {


                    if (i==6)
        {
            //System.out.println(current.data);
            previous.next = current.next;
            break;
        }
                    previous=current;
                    current = current.next;
                    i++;

    }

}


public static void main(String args[])
{
    linkedList list = new linkedList();
    linkedList.Node tail = linkedList.new Node(0);
//  list.Node tail = list.Node(0);


    Node head = tail;

    for (int i=1;i<=20;i++)
    {
        head = head.addToHead(i);
    }

    findn(head);
    while(head!=null)
    {
        System.out.println(head.data);
        head = head.next;
    }
}
}

我在主要功能中的问题是,我尝试使用外部类创建一个节点。 但是,即使我遵循正确的语法,语法也会使我出错。 我想知道此语句“ linkedList.Node tail = linkedList.new Node(0);”有什么问题。

作为非静态内部类的Node需要其封闭类的实例 linkedList是类名。 它没有引用该类的实例。 所以应该

list.new Node()

如果您遵守Java命名约定,那就更加清楚了:变量以小写字母开头,而类以大写字母开头。

您可能应该在类linkedList,addToTail()中创建一个方法:

public void addToTail(int k) {
    Node tail = new Node(k);
    //loop through all the nodes in the list and add "tail" to the end
}

然后,您可以在main()中调用lst.addToTail(k),其中lst将是linkedList类的对象。

顺便说一句,当您使用小写字母开头类名称时,它会使代码难以读取。 它们通常以Java中的大写字母开头。 调用类LinkedList(以大写字母开头)也令人困惑,因为它可能会误认为标准的java.util.LinkedList,因此也许可以将其命名为LinkedList0或其他名称。

暂无
暂无

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

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