java - 请解释 intern() 方法的功能

标签 java

<分区>

Possible Duplicate:
When should we use intern method of String?
what is string interning?

请解释以下代码的内部工作原理:

System.out.println(new String("ABC").intern()==new String("ABC").intern());

在上面的代码中,它打印了“true”。但是根据 java 规则,在 new 运算符的情况下,它总是创建一个新对象。 object.intern() 方法还在字符串池中创建一个对象。所以我的问题是,在上面的代码中创建了多少个对象。

据我所知,将创建 3 个新对象。一个进入String池,new操作符会创建两个匿名对象。但我不确定。

如果我错了请解释。

最佳答案

假设优化器不聪明,会创建两个对象。 (足够聪明的优化器可以将其优化为无条件的 true,在这种情况下不会创建任何对象。)

tl;dr 版本:您的答案 3 几乎是正确的,只是进入字符串池的字符串不是作为该语句的一部分生成的;它已经创建。

首先,让我们把"ABC" 文字移开。它在运行时表示为 String 对象,但它存在于 pergen 中,并且在 JVM 的整个生命周期中只创建一次。如果这是第一个使用该字符串文字的类,则它是在类加载时创建的(请参阅 JLS 12.5 ,其中指出该字符串是在类加载时创建的,除非它以前存在)。

因此,第一个 new String("ABC") 创建了一个 String,它只是 copies the reference (但不创建新对象)到 chars 数组,并从表示 "ABC" 文字的字符串散列(同样,它不是作为该行的一部分创建的)。 .intern() 方法然后查看 permgen 中是否已经有一个相等的字符串。它是(它只是代表文字开头的字符串),所以这就是该函数返回的内容。所以,new String("ABC").intern() == "ABC"。参见 JLS 3.10.5 ,特别是:

Moreover, a string literal always refers to the same instance of class String. This is because 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.

第二次出现 new String("ABC").intern() 时,同样的事情发生了。而且,由于 intern() 方法都返回与 "ABC" 文字相同的对象,因此它们表示相同的值。

分解一下:

String a = new String("ABC"); // a != "ABC"
String aInterned = a.intern(); // aInterned == "ABC"

String b = new String("ABC"); // b != "ABC"
String bInterned = b.intern(); // bInterned == "ABC"

System.out.println(new String("ABC").intern()==new String("ABC").intern());
                                            // ... is equivalent to... 
System.out.println(aInterned == bInterned); // ...which is equivalent to...
System.out.println("ABC" == "ABC");         // ...which is always true.

关于java - 请解释 intern() 方法的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14393231/

相关文章:

java - 获取 [SqlExceptionHelper] 不正确的字符串值 : '\xF0\x9F\x90\xBE V...' although the table is in UTF-8

java - Spring 安全 : AuthenticationProcessingFilter is called twice

java - 是否可以在 spring-data-mongodb 中注入(inject)自定义 Jackson ObjectMapper?

java - 如果组件已经可用,我们是否应该在 Mule 中使用 Java 组件? Mule 性能和优化

java - HystrixRuntime异常 : TestCommand fallback execution rejected

java - 如何为 java.sql.DatabaseMetaData#g​​etTables 创建不区分大小写的模式?

java - 通过java将数据追加到xlsx文件中

java - 为什么java.lang.Object中的clone()方法受到保护?

java - 将文件读取到具有固定缓冲区大小的 byte[] 会生成重复的输出

java - Spring Boot 即时重置数据源