简体   繁体   English

为什么我没有收到NullPointerException

[英]Why am I NOT getting a NullPointerException

Why is it, that when I add an object, to my ArrayList, which Should be passing it a Reference to the object, then I make the object equal to null, it outputs perfectly fine. 为什么会这样,当我将一个对象添加到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);
    }

The test constructor goes as: 测试构造函数如下:

int x = 0;

Test()
{
    x = 50;
}

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

Yet, the output is 50, 50, 50 instead of 50, 50, null 但是,输出为50、50、50,而不是50、50(空)

When you call add , the ArrayList now has its own reference to the same object. 当您调用addArrayList现在具有对相同对象的自己的引用。

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

That is unaffected by setting your reference test to null . 通过将参考test设置为null不会受到影响。

test ----> null

testList ----> Test() object

Because there is a difference between Reference Types and Value Types in Java. 因为Java中的引用类型和值类型之间存在差异。

You add a reference to the value (aka an object) to the list, then you delete the reference. 您将对值(也称为对象)的引用添加到列表中,然后删除该引用。 However the value is still there in memory, and the list still has a reference to that value, despite your original reference being nullified 但是,该值仍然存在于内存中,尽管原始引用已为空,但列表仍然具有对该值的引用。

When you are passing reference to object to ArrayList you actually create yet another reference that is used by ArrayList to refer to the object. 当您将对对象的引用传递给ArrayList ,实际上创建了另一个引用,ArrayList使用该引用来引用该对象。

When you assign null to variable test you actually "cancel" your reference. 当您将null分配给变量test您实际上“取消”了您的引用。 Nothing happens with reference of array list. 引用数组列表没有任何反应。

Even simpler. 更简单。

If you have 2 variables: one and two: 如果您有2个变量:一个和两个:

Test one = new Test()
Test two = one;

At this point both references point to the same object. 此时,两个引用均指向同一对象。

one = null;

Now one is null, but two still refers to that object. 现在one为空,但是two仍然引用该对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM