简体   繁体   English

JVM如何处理对对象的引用,然后使用new关键字将其设置为新的对象值

[英]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.

相关问题 “new”关键字是否会更改对象引用的值? - Does the “new” keyword change the value of an object reference? 为什么jvm每次使用new关键字创建字符串时都会创建新的字符串Object - Why jvm create new string Object each time we create string using new keyword 如果使用 new 关键字调用构造函数,它是否会创建一个对象? - If a constructor is called with new keyword, does it create an object? 使用new关键字创建单个对象 - Create single object using new keyword 不使用新关键字创建字符串 Object - String Object creation without using new keyword JVM如何确保新对象的内存分配的线程安全性 - How JVM ensures thread safety of memory allocation for a new object JVM 如何在内部使用以下表达式: Object c = new SomeClass(); - How JVM works internally with follow expression: Object c = new SomeClass(); 使用 new 关键字和使用 clone 方法创建对象的区别 - Difference between creating an object using new keyword and using clone method 如何在java中的ArrayList中将新值设置为现有对象 - How to set new value into existing object in ArrayList in java 如何在java 8中使用stream过滤两个列表对象并将值设置为新的List - How to using stream in java 8 filter two list object and set value to new List
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM