java 将对象分配给 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13927077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:28:39  来源:igfitidea点击:

Assign an object to null

java

提问by shirley

If I instantiate an object and pass it to an function, in this function I assign this object to null. It seems when return from the function, the object still there.

如果我实例化一个对象并将它传递给一个函数,在这个函数中我将这个对象分配给 null。似乎从函数返回时,对象仍然存在。

I just want to know when I assign null, what happens.

我只想知道当我分配 null 时会发生什么。

回答by Patricia Shanahan

You can never assign to an object. All you ever have are primitives and references. A reference is either null or a pointer to an object of suitable class.

你永远不能分配给一个对象。你所拥有的只是基元和引用。引用要么是空值,要么是指向合适类的对象的指针。

Java arguments are passed by value. Your called method got a copy of a reference. It made that reference null. The calling method has its own reference which was unaffected by any assignments to the passed copy. That reference still points to the object.

Java 参数按值传递。你被调用的方法得到了一个引用的副本。它使该引用为空。调用方法有它自己的引用,它不受对传递的副本的任何赋值的影响。该引用仍然指向该对象。

回答by Perception

Arguments to methods in Java are 'pass-by-value', which means you are passing a copy of the object reference into the method. Assigning this reference a value of null will change its value withinthe method call, but does nothing to the reference outside the method, since its a copy. Illustrated with code:

Java 中方法的参数是“按值传递”,这意味着您将对象引用的副本传递到方法中。为这个引用分配一个 null 值将方法调用中改变它的值,但对方法外的引用没有任何影响,因为它是一个副本。用代码说明:

void doSomething(final String input) {
    input = null;
    System.out.println("Input is: " + input); // prints null
    return;
}

final String name = "Bob";
doSomething(name);
System.out.println("Name is: " + name); // prints 'Bob'

回答by vishal_aim

when you instantiate an object and pass it to a function, and inside the function you reassign that to null or whatever, at the calling side it is not reflected as arguments are pass by value (copy of reference in case of objects), at calling side it'll still point to the old object. If you want to restrict reassigning in a method, you can use finalkeyword in method parameter

当您实例化一个对象并将其传递给一个函数时,在函数内部,您将其重新分配为 null 或其他任何内容,在调用端它不会反映为参数按值传递(对象情况下的引用副本),在调用时一边它仍然会指向旧对象。如果要限制方法中的重新分配,可以final在方法参数中使用关键字

回答by BlackJoker

When you pass the object reference to a function(Java always call it method),in the method scope,a new reference is created on stack memory,but they point to the same object in heap memory.So if you assign null to the new reference,Only this reference's link to that object is break,It does not affect the prevous one.

当您将对象引用传递给函数时(Java 总是调用它的方法),在方法范围内,会在堆栈内存上创建一个新引用,但它们指向堆内存中的同一对象。因此,如果您将 null 分配给新的引用,只有这个引用到那个对象的链接是断开的,不影响上一个。