当我使用匿名内部类创建节点时。当我打印所有键时,它们打印为 0,而不是我在匿名类声明中分配的值。难道我做错了什么?这是我的代码:
public class LinkedListTest {
Node head;
public void addInOrder(final int value) {
if (head == null) {
head = new Node() {
int key = value;
};
}
else if(head.key > value) {
final Node temp = head;
head = new Node() {
int key = value;
Node next = temp;
};
}
else {
Node theNode = head;
while(theNode.key < value) {
if (theNode.next == null) {
theNode.next = new Node() {
int key = value;
};
return;
}
else if(theNode.next.key > value) {
final Node temp = theNode.next;
theNode.next = new Node() {
int key = value;
Node next = temp;
};
return;
}
theNode = theNode.next;
}
}
}
这是我的节点的类声明:
class Node {
int key;
Node next;
}
这是我的打印方法:
public void printAll(Node hasNode) {
if (hasNode != null) {
System.out.println(hasNode.key);
if (hasNode.next != null) {
printAll(hasNode.next);
}
}
}
最佳答案
这是因为您没有为 Node
中的字段赋值,而是为匿名子类中具有相同名称的字段赋值。
向Node
添加构造函数,并且不创建匿名子类:
class Node {
int key;
Node next;
Node(int key, Node next) {
this.key = key; this.next = next;
}
}
您可以选择添加第二个构造函数,它只接受 key :
Node(int key) {
this(key, null);
}
另一种方法是调用new Node(key, null)
。
关于java - java中匿名内部类成员不可访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34189159/