gpt4 book ai didi

java - 为什么我没有收到 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 08:05:40 30 4
gpt4 key购买 nike

为什么当我将一个对象添加到我的 ArrayList 时,它应该向它传递对该对象的引用,然后我使该对象等于 null,它输出完全正常。

    ArrayList<Test> testList = new ArrayList<>();

Test test = new Test();
System.out.println(test);

testList.add(test);

for(Test t : testList)
{
System.out.println(t);
}

test = null;

for(Test t : testList)
{
System.out.println(t);
}

测试构造函数如下:

int x = 0;

Test()
{
x = 50;
}

public String toString()
{
return x + "";
}

然而,输出是 50, 50, 50而不是 50、50、null

最佳答案

当您调用 add 时,ArrayList 现在拥有对同一对象的自己的引用。

test ----> Test() object
^
testList ----|

将引用 test 设置为 null 不会影响这一点。

test ----> null

testList ----> Test() object

关于java - 为什么我没有收到 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21889478/

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