我试图通过Java解决LinkedList的问题,但我发现了静态内部类的概念,我卡在这里了!
我的代码正在运行,但无法理解静态类对象是如何创建的
public class findNthNodeInLL {
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
next = null;
}
}
int findNthNode(Node head, int count) {
int pos = 0;
Node ptr = head;
while(ptr != null && pos != count) {
pos++;
ptr = ptr.next;
}
return ptr.data;
}
public static void main(String[] args) {
findNthNodeInLL ll = new findNthNodeInLL();
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
System.out.println(ll.findNthNode(head,3));
}
}
内部类 Object 即 head 是在没有外部类的任何引用的情况下创建的。甚至调用构造函数并在没有任何外部类引用的情况下创建内存。
这里的实际情况是怎样的?怎么了?为什么我们不对内部类构造函数或对象使用任何外部类引用?
也许我错过了一些东西。请帮我理解这里的场景。
您在外部类本身内部使用静态类,因此您不要放置封闭类名称。静态嵌套类在行为上类似于任何静态字段。
但是如果要在外部类之外实例化静态嵌套类,则必须在其定义上放置封闭类名称或使用对外部类的引用。
例如 :
public class Main {
static class NodeInside {
int data;
NodeX.Node next;
NodeInside(int data) {
this.data = data;
next = null;
}
}
public static void main(String[] args) {
NodeX ll = new NodeX();
NodeX.Node head = new NodeX.Node(1); // need to put the enclosing class name
NodeInside nodeInside = new NodeInside(1); // no need to put the enclosing class
}
}
class NodeX{
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
next = null;
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句