gpt4 book ai didi

java - java中的字符串和内存分配?

转载 作者:行者123 更新时间:2023-12-01 07:14:19 25 4
gpt4 key购买 nike

我一直想知道的一件事,如果我有这样的方法:

String replaceStuff (String plainText) {
return plainText.replaceAll("&", "&");
}

它是否会一直为“&”创建新的 String 对象,以及被 GC 销毁并在下一次调用时再次重新创建的“&”?例如。理论上这样做会更好

final String A ="&";
final String AMP ="&";

String replaceStuff (String plainText) {
return plainText.replaceAll(A, AMP);
}

我认为这可能是一个比现实生活问题更理论的问题,我只是好奇内存管理在这方面是如何处理的。

最佳答案

没有。字符串文字被保留。即使您在其他地方使用相等的文字(或其他常量),您仍然会引用同一个对象:

Object x = "hello";
Object y = "he" + "llo";

System.out.println(x == y); // Guaranteed to print true.

编辑:JLS 在第 3.10.5 节中保证了这一点

String literals-or, more generally, strings that are the values of constant expressions (§15.28)-are "interned" so as to share unique instances, using the method String.intern.

第 15.28 节展示了 + 运算符作为一个运算包含在内,该运算可以从其他两个常量生成一个新常量。

关于java - java中的字符串和内存分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6979933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com