gpt4 book ai didi

java - Java 中的链表引用

转载 作者:行者123 更新时间:2023-11-29 03:22:56 26 4
gpt4 key购买 nike

如果我有一个 ListNode 类,它是

public class ListNode{
int data;
ListNode nextNode;
}

和一个列表类,它是

public class List{
private ListNode firstNode;
private ListNode lastNode;
private String name;

public List(String listName){
name = listName;
firstNode = lastNode = null;
}
}

最后一句“firstNode = lastNode = null”是什么意思? firstNode.data = null 还是 firstNode.nextNode = null?

最佳答案

编辑:看来我回答了错误的问题。正如下面评论中提到的 OP:

Sorry, my question may not be clear enough, what I am truly confusing is that when executing "firstNode = null", wether firstNode.data = null or firstNode.nextNode = null because firstNode is a object of type ListNode, which has int data and listNode type instances.

赋值firstNode = null后,没有.data.nextNode。您必须先将 firstNode 分配给 new ListNode()

一旦你这样做了,它的 data 成员将被初始化为 0 而它的 nextNode 成员将被初始化为 null,因为如果没有进行显式初始化,这些是成员字段的默认初始值。但是同样,您需要先实例化一个 ListNode 并将其分配给 firstNode,否则如果您尝试访问它,您将得到一个 NullPointerException而它是 null


原始答案,回复:firstNode = lastNode = null

它将 firstNodelastNode 都分配给 null

这是一个常用的句法技巧,它利用了赋值表达式作为一个整体计算赋值后变量值的事实:

    a = b = 1   
=> a = (b = 1) (b = 1) assigns b then evaluates to 1
=> a = 1

只要类型兼容,您可以将任意多个链接在一起:

    a = b = c = d = 1
=> a = b = c = (d = 1) (d = 1) assigns d then evaluates to 1
=> a = b = (c = 1) (c = 1) assigns c then evaluates to 1
=> a = (b = 1) (b = 1) assigns b then evaluates to 1
=> a = 1

不兼容的类型会导致错误:

Integer x;
Double y;
x = y = null; // error: cannot convert from Double to Integer

这与您在执行以下操作时使用的技巧相同:

int ch;
while ((ch = input.read()) != -1) {
...
}

来自 JLS 15.26 :

At run time, the result of the assignment expression is the value of the variable after the assignment has occurred.

关于java - Java 中的链表引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22586896/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com