gpt4 book ai didi

Java-使用 new 关键字创建字符串对象

转载 作者:搜寻专家 更新时间:2023-11-01 01:02:09 27 4
gpt4 key购买 nike

我知道字符串字面量和新字符串对象之间的区别,也知道它在内部是如何工作的。但我的问题有点超前。当我们使用 new 关键字创建字符串对象时

String str = new String("test");

在这种情况下,我们传递的是字符串类型的参数。我的问题是这个字符串是在哪里生成的——堆或字符串常量池还是其他地方?

据我所知,这个参数是一个字符串文字,所以它应该在字符串常量池中。如果是这样,那么 intern 方法有什么用 - 只是链接变量 str 到常量池?因为 "test" 已经可用了。

如果我误解了这个概念,请澄清我。

最佳答案

语句 String str = new String("test"); 创建了一个字符串对象,它像任何其他对象一样存储在堆上。作为参数传递的字符串文字 "test" 存储在字符串常量池中。

String#intern() 检查字符串常量是否已在字符串池中可用。如果已经有一个它返回它,否则它创建一个新的并将它存储在池中。查看Javadocs :

Returns a canonical representation for the string object.

A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

从JDK7开始,interned字符串存储在堆上。这是来自 release notes of JDK7 :

In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences.

关于Java-使用 new 关键字创建字符串对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28427483/

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