假设我有一个节点类型。
public class Node{
private Node next;
private int data;
// other methods including constructor and setting next reference.
}
或者使用 null
作为未初始化的值,如下所示:
public class Node{
private Node next = null;
private int data;
}
最佳答案
public class Node{
private Node next; //initialized to null
private int data; //initialized to 0
// other methods including constructor and setting next reference.
}
这里的 next
和 data
是实例变量,与局部变量不同,它们被赋予了默认值。因此 next
是一个 Object 将被分配空值,而 data
是一个 int 将被初始化为 0。
因此,您的每个 Node 实例都将数据初始化为 0,下一个 Node 设置为 null。如果您需要一些特定的初始化,您可以在构造函数中进行或使用相应的 getter/setter 方法。
关于java - 什么时候在java中使用null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29497429/