[英]How does JVM handle references to an object that is then set to a new object value using new keyword
I'm curious about what happens to java object references that are passed through a method param, set to a class scoped variable in the class where the method lives, and then the original object passed as a param is set to a new value using the new keyword. 我很好奇通过方法参数传递的java对象引用会发生什么,将其设置为方法所在的类中的类范围变量,然后将使用param传递的原始对象设置为使用新关键字。
My understanding is that objects are passed by reference not value in method params, but what happens in the case when the original object is set to a new value using = new? 我的理解是,对象是通过引用传递的,而不是方法参数中的值,但是当使用= new将原始对象设置为新值时会发生什么呢? Does java create a new location in memory for this new object so that pointers to the existing object remain in tact? Java是否会在内存中为此新对象创建一个新位置,以使指向现有对象的指针保持原样?
Hope I'm not asking a dumb question. 希望我不要问一个愚蠢的问题。 - Duncan -邓肯
You can't pass Objects and you can't set Objects. 您不能传递对象,也不能设置对象。
You only have primitives and references. 您只有原语和引用。
A references is an address, typically a 4-byte value like an int
引用是地址,通常是4字节的值,例如int
So when you change a reference it is no different to setting an int
value to something else. 因此,当您更改引用时,将int
值设置为其他值没有什么不同。 In fact, setting a reference to null
can be exactly the same as setting an int to 0
实际上,将引用设置为null
可以与将int设置为0
完全相同。
Does java create a new location in memory for this new object so that pointers to the existing object remain in tact? Java是否会在内存中为此新对象创建一个新位置,以使指向现有对象的指针保持原样?
When you create a new object, new memory is always used. 创建新对象时,始终使用新内存。 This will happen even if the old object no longer used anywhere else. 即使旧对象不再在其他任何地方使用,也会发生这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.