java - java中匿名内部类成员不可访问

标签 java inner-classes anonymous-class anonymous-inner-class

当我使用匿名内部类创建节点时。当我打印所有键时,它们打印为 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/

相关文章:

java - 如何隐藏/删除 SWT 表中的列

java - 匿名类声明中的语句

Java 匿名类效率影响

java - 通过 Java Servlet 转发到自身的网页在浏览器后退/前进按钮上的行为不正确

java - 非阻塞风格有什么好处?

java - 如何从全文中选择特定片段?

java - java如何实现内部类闭包?

java - 什么是静态嵌套类?

python - 如何使用Unittest在Python中编写内部类测试方法

java - 无法在匿名类中使用导入的类