java - 使用new创建字符串对象及其与intern方法的比较

标签 java string

我在Kathy Sierra的书中读到,当我们使用像String s = new String("abc")这样的new运算符创建String时,在这种情况下,因为我们使用了new关键字,Java将在正常(非池)中创建一个新的String对象) 内存,s 将引用它。此外,文字“abc”将被放入池中。

intern() 表示如果 String 池已经包含字符串,则返回池中的字符串,否则,将 String 对象添加到池中,并返回对此 String 对象的引用。

如果使用 new 创建字符串“abc”时也将字符串放入池中,那么 intern() 表示如果字符串池包含该字符串,则返回池中的字符串,否则字符串对象将添加到池中。

另外我想知道如果我们使用 new 创建一个 String 那么实际上创建了多少个对象?

最佳答案

TL;DR:如果您确实需要执行new String("abc"),您就会知道您需要这样做,并且知道为什么。这种情况非常罕见,以至于可以说您永远不需要这样做。只需使用“abc”

<小时/>

长版本:

当您使用代码 new String("abc") 时,会在不同时间发生以下情况:

  • 加载包含该代码的类时,如果内部池中尚不存在包含字符 "abc" 的字符串,则会创建该字符串并将其放在那里。
  • new String("abc")代码运行时:
    • 对实习池中的“abc”字符串的引用被传递到String构造函数中。
    • 通过复制传入构造函数的 String 中的字符来创建并初始化 String 对象。
    • 新的 String 对象将返回给您。

If string "abc" when created using new also placed the string in the pool, then why does intern() says that string from the pool is returned if String pool contains the string otherwise the string object is added to the pool.

因为这就是实习生所做的事情。请注意,在字符串文字上调用 intern 是无操作的;字符串文字都会自动保留。例如:

String s1 = "abc";               // Get a reference to the string defined by the literal
String s2 = s1.intern();         // No-op
System.out.println(s1 == s2);    // "true"
System.out.println(s1 == "abc"); // "true", all literals are interned automatically

Also I want to know if we create a String using new then actually how many objects get created?

您至少创建一个 String 对象(新的、非内部对象),也可能创建两个(如果该文字尚未在池中;但同样,这一点发生得更早,当加载类文件的文字时):

String s1 = "abc";            // Get a reference to the string defined by the literal
String s2 = new String(s1);   // Create a new `String` object (guaranteed)
System.out.println(s1 == s2); // "false"
String s3 = s2.intern();      // Get the interned version of the string with these characters
System.out.println(s1 == s3); // "true"

关于java - 使用new创建字符串对象及其与intern方法的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10571158/

相关文章:

java - Spring - 如何从 application.properties 中的 spring.datasource 配置 OracleDataSource

java - Android runOnUiThread线程安全

java - Spring Boot 启动器依赖项是否已准备好生产?

python - 计算主题标签的功能

C++,在 If-Else 语句中访问字符串字符(初学者问题)

Java 并发文件写入 - 应该会失败

java - 将一个实例注入(inject)多个 bean

python - write() 与 writelines() 和连接字符串

java - 在 java 或 joda time 中使用格式化字符串添加分钟

algorithm - 计算上下文相关的文本相关性