java - 什么时候在java中使用null?

标签 java refactoring

假设我有一个节点类型。

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.
}

这里的 nextdata 是实例变量,与局部变量不同,它们被赋予了默认值。因此 next 是一个 Object 将被分配空值,而 data 是一个 int 将被初始化为 0。

因此,您的每个 Node 实例都将数据初始化为 0,下一个 Node 设置为 null。如果您需要一些特定的初始化,您可以在构造函数中进行或使用相应的 getter/setter 方法。

关于java - 什么时候在java中使用null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29497429/

相关文章:

java - eclipse 插件 : How to programmatically select text in editor?

java - 使用 .length 方法时得到不兼容的类型

java - 如何使用按钮操作事件来调用其他类?

database - 最佳实践 : Storing a workflow state of an item in a database?

java - 重写泛型类中的方法

SQL 数据库重构工具

java - 自定义 ParseQueryAdapter 未填充 Android ListView

c# - 我如何重构/扩展以下模型

ios - 重构 iOS 代码 : Decreasing the number of lines of code

c# - 如何使用 C# 访问 jar 文件(其中包含 Java .class 作为 API)