将类实例变量引用重新指派为局部变量引用


private Node firstNode = null;
public void test() {
int item = 0;
Node lastNode;
lastNode = firstNode;
newNode = new Node(item);
firstNode = newNode;
//Expected lastNode to now point to newNode. However, I get a nullpointer Exception because lastNode is still null

为什么lastNode仍然为null?既然firstNode被重新分配给引用newNode,那么lastNode现在不应该引用newNode吗?

null不是有效的对象实例,因此没有为其分配内存。它只是一个值,表示对象引用当前没有引用对象。来自JVM规范:Java虚拟机规范没有强制要求对null进行编码的具体值。

所以,在线:

lastNode = firstNode;

您没有为lastNode指定对firstNode对象的引用。当您更改firstNode时,lastNode将保持为空。

由于private Node firstNode = null;,您将"NullPointer"分配给lastNode所以…lastNode总是空的,除了firstNode有non-null引用。

最新更新