简体   繁体   English

字符串-Java中的堆栈和堆

[英]Strings - Stack and heap in java

I know that Strings are stored on the heap and the reference to them is stored on the stack. 我知道字符串存储在堆中,对它们的引用存储在堆栈中。 So in the code below one would point to "John" on the heap from the stack and likewise two would point to "Smith" on the heap from the stack. 因此,在下面的代码中, one将指向堆栈中堆上的"John" ,同样, two将指向堆栈中堆上的"Smith"

So what happens when i do one = two ? 那么当我做one = two时会发生什么呢? Does one now point to where two points to because two contains a reference to a point on the heap or does it change the "John" on the heap to "Smith" ? 难道one现在指向哪里two点,因为two包含堆一个参照点或不会修改"John"就堆到"Smith"

String one;
one = "John";
String two = "Smith"
one = two;

In your example, one now points to the same place as two . 在您的示例中, one现在指向two相同的位置。 The original string on the heap "John" becomes garbage and is subject to garbage collection. "John"上的原始字符串变为垃圾,并进行垃圾回收。

It's not possible to see in this example because String is immutable, but if these were mutable data structures such as an ArrayList , then modifying the object through one would make the same change visible through two , because they point to the same object. 在此示例中不可能看到,因为String是不可变的,但是如果它们是可变的数据结构(例如ArrayList ,则通过one对象修改对象将使得通过two对象看到相同的更改,因为它们指向同一个对象。

Now one will point to the two . 现在one将指向two
Since all string are immutable then when they are created then they are stored in heap and referenced by variable but when you make or assign new variable to same string then it will not explicitly create new string but just reference to same string which is in heap 由于所有字符串都是不可变的,因此在创建它们时会将它们存储在堆中并由变量引用,但是当您将新变量创建或分配给同一字符串时,它将不会显式创建新字符串,而只会引用heap相同的字符串
在此处输入图片说明

from above picture you can easily understand the concept of immutability. 从上面的图片中,您可以轻松理解不变性的概念。
for reference Where does java reference variable stored? 供参考Java引用变量存储在哪里?

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

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