下面两个Java中链表的实现是否相同?
Are the following two implementations of linked list in Java same?
实施 1 ->
public class Node<T> {
T data;
Node<T> next; // next should point to a node which contains data of type T
Node(T data){
this.data = data;
this.next = null;
}
}
实施 2 ->
public class Node<T> {
T data;
Node<T> next; // next should point to a node which contains data of type T
Node(T data){
this.data = data;
}
}
由于在JAVA中引用默认赋值为null,所以上面两种实现是否相同?我以前用 C++ 实现过链表,但对 JAVA 实现感到困惑
两种实现方式相同。
在您的案例中,创建新对象的阶段包括几个阶段(简化):
- 在字段
data, next
上设置默认值,因为它们是对对象 class 实例的引用,那么它们将是 null
.
- 构造函数的执行,在第一个实现中将
next
字段设置为 null 值是没有意义的,因为它已经在第一阶段被 Java 设置为 null。
还有其他可能的阶段,例如,当您从另一个 class 继承时,在这种情况下,父 class 构造函数将在当前 class 的构造函数之前被调用。
查看文档或文章以获取更多详细信息(例如 - https://farenda.com/java/java-initialization-order/)。
实施 1 ->
public class Node<T> {
T data;
Node<T> next; // next should point to a node which contains data of type T
Node(T data){
this.data = data;
this.next = null;
}
}
实施 2 ->
public class Node<T> {
T data;
Node<T> next; // next should point to a node which contains data of type T
Node(T data){
this.data = data;
}
}
由于在JAVA中引用默认赋值为null,所以上面两种实现是否相同?我以前用 C++ 实现过链表,但对 JAVA 实现感到困惑
两种实现方式相同。 在您的案例中,创建新对象的阶段包括几个阶段(简化):
- 在字段
data, next
上设置默认值,因为它们是对对象 class 实例的引用,那么它们将是null
. - 构造函数的执行,在第一个实现中将
next
字段设置为 null 值是没有意义的,因为它已经在第一阶段被 Java 设置为 null。 还有其他可能的阶段,例如,当您从另一个 class 继承时,在这种情况下,父 class 构造函数将在当前 class 的构造函数之前被调用。 查看文档或文章以获取更多详细信息(例如 - https://farenda.com/java/java-initialization-order/)。