简体   繁体   English

重新初始化没有更多内存的字符串数组

[英]Re initialize a string array with no more memory left

In Java, since strings are immutable, when we re assign a string Array element to a different string and are out of memory would it compile and run fine? 在Java中,由于字符串是不可变的,因此当我们将字符串Array元素重新分配给其他字符串并且内存不足时,它可以编译并正常运行吗?

my understanding is for example if there are 2 elements in a string array, "John" and "Henry", when i change the array's second element to "Tom", what happens to "Henry" since it cant be really over written (immutable strings) and behind the scenes is java pointing to a new location (should array locations not be next to each other? ). 我的理解是,例如,如果字符串数组中有两个元素“ John”和“ Henry”,当我将数组的第二个元素更改为“ Tom”时,“ Henry”会发生什么,因为它不能被真正覆盖(不可变)字符串),并且在后台Java指向一个新位置(数组位置不应该彼此相邻吗?)。

I ran a test and it successfully changed the second element to Tom. 我进行了测试,它成功地将第二个元素更改为汤姆。 It compiled and ran fine. 它编译并运行良好。 As per my understanding this should not have been allowed because strings cant be over written and array are supposed to be consecutive memory locations. 根据我的理解,这不应该被允许,因为不能覆盖字符串,并且数组应该是连续的内存位置。 please clarify - thanks 请澄清-谢谢

Each cell of your array contains the address of a String instance. 数组的每个单元格都包含一个String实例的地址。 When you change the value of the second cell it just points to another String instance, and if the instance previously pointed by that cell is no longer pointed by any other variable, might be chosen for garbage collection. 当您更改第二个单元格的值时,它仅指向另一个String实例,并且如果该单元格先前指向的实例不再由任何其他变量指向,则可以选择进行垃圾回收。

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

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