268

什么是Java 中的字符串实习,什么时候应该使用它,为什么

4

8 回答 8

274

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern()

基本上对一系列字符串执行 String.intern() 将确保所有具有相同内容的字符串共享相同的内存。因此,如果您有 'john' 出现 1000 次的名称列表,则通过实习可以确保只有一个 'john' 实际分配了内存。

这对于减少程序的内存需求很有用。但请注意,缓存由 JVM 维护在永久内存池中,与堆相比,其大小通常有限,因此如果您没有太多重复值,则不应使用实习生。


更多关于使用 intern() 的内存限制

一方面,确实可以通过内化 String 重复项来删除它们。问题是内部化的字符串进入了永久代,这是 JVM 中为非用户对象(如类、方法和其他内部 JVM 对象)保留的区域。这个区域的大小是有限的,通常比堆小得多。在 String 上调用 intern() 具有将其从堆移到永久代的效果,并且您可能会耗尽 PermGen 空间。

-- 来自: http: //www.codeinstructions.com/2009/01/busting-javalangstringintern-myths.html


从 JDK 7(我的意思是在 HotSpot 中)开始,有些事情发生了变化。

在 JDK 7 中,interned 字符串不再分配在 Java 堆的永久代中,而是与应用程序创建的其他对象一起分配在 Java 堆的主要部分(称为年轻代和年老代)中. 此更改将导致更多数据驻留在主 Java 堆中,而永久代中的数据更少,因此可能需要调整堆大小。由于此更改,大多数应用程序只会看到相对较小的堆使用差异,但加载许多类或大量使用 String.intern() 方法的大型应用程序将看到更显着的差异。

-- 来自Java SE 7 的特性和增强

更新:从 Java 7 开始,内部字符串存储在主堆中。http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html#jdk7changes

于 2012-05-14T07:24:05.150 回答
79

有一些“吸引人的面试”问题,比如为什么你会得到平等!如果您执行以下代码。

String s1 = "testString";
String s2 = "testString";
if(s1 == s2) System.out.println("equals!");

如果你想比较字符串,你应该使用equals(). 上面将打印 equals 因为编译器testString已经为你实习了。您可以使用 intern 方法自己对字符串进行实习,如先前的答案所示......

于 2015-06-01T14:30:31.577 回答
47

捷豹路虎

JLS 7 3.10.5对其进行了定义并给出了一个实际示例:

此外,字符串字面量总是引用 String 类的同一个实例。这是因为字符串字面量 - 或者更一般地说,作为常量表达式值的字符串(第 15.28 节) - 是“内部的”,以便使用 String.intern 方法共享唯一实例。

示例 3.10.5-1。字符串文字

由编译单元组成的程序(§7.3):

package testPackage;
class Test {
    public static void main(String[] args) {
        String hello = "Hello", lo = "lo";
        System.out.print((hello == "Hello") + " ");
        System.out.print((Other.hello == hello) + " ");
        System.out.print((other.Other.hello == hello) + " ");
        System.out.print((hello == ("Hel"+"lo")) + " ");
        System.out.print((hello == ("Hel"+lo)) + " ");
        System.out.println(hello == ("Hel"+lo).intern());
    }
}
class Other { static String hello = "Hello"; }

和编译单元:

package other;
public class Other { public static String hello = "Hello"; }

产生输出:

true true true true false true

虚拟机

JVMS 7 5.1 说实习是通过专用CONSTANT_String_info结构神奇而有效地实现的(与大多数其他具有更通用表示的对象不同):

字符串字面量是对 String 类实例的引用,它派生自类或接口的二进制表示形式的 CONSTANT_String_info 结构(第 4.4.3 节)。CONSTANT_String_info 结构给出了构成字符串文字的 Unicode 代码点序列。

Java 编程语言要求相同的字符串文字(即包含相同代码点序列的文字)必须引用 String 类的相同实例(JLS §3.10.5)。此外,如果对任何字符串调用 String.intern 方法,则结果是对同一类实例的引用,如果该字符串以文字形式出现,则会返回该类实例。因此,以下表达式的值必须为 true:

("a" + "b" + "c").intern() == "abc"

为了派生字符串文字,Java 虚拟机检查 CONSTANT_String_info 结构给出的代码点序列。

  • 如果先前已在包含与 CONSTANT_String_info 结构给出的相同的 Unicode 代码点序列的类 String 的实例上调用了方法 String.intern,则字符串字面量推导的结果是对同一类 String 实例的引用。

  • 否则,将创建一个 String 类的新实例,其中包含由 CONSTANT_String_info 结构给出的 Unicode 代码点序列;对该类实例的引用是字符串文字派生的结果。最后,调用新 String 实例的 intern 方法。

字节码

让我们反编译一些 OpenJDK 7 字节码,看看实习的效果。

如果我们反编译:

public class StringPool {
    public static void main(String[] args) {
        String a = "abc";
        String b = "abc";
        String c = new String("abc");
        System.out.println(a);
        System.out.println(b);
        System.out.println(a == c);
    }
}

我们在常量池上有:

#2 = String             #32   // abc
[...]
#32 = Utf8               abc

main

 0: ldc           #2          // String abc
 2: astore_1
 3: ldc           #2          // String abc
 5: astore_2
 6: new           #3          // class java/lang/String
 9: dup
10: ldc           #2          // String abc
12: invokespecial #4          // Method java/lang/String."<init>":(Ljava/lang/String;)V
15: astore_3
16: getstatic     #5          // Field java/lang/System.out:Ljava/io/PrintStream;
19: aload_1
20: invokevirtual #6          // Method java/io/PrintStream.println:(Ljava/lang/String;)V
23: getstatic     #5          // Field java/lang/System.out:Ljava/io/PrintStream;
26: aload_2
27: invokevirtual #6          // Method java/io/PrintStream.println:(Ljava/lang/String;)V
30: getstatic     #5          // Field java/lang/System.out:Ljava/io/PrintStream;
33: aload_1
34: aload_3
35: if_acmpne     42
38: iconst_1
39: goto          43
42: iconst_0
43: invokevirtual #7          // Method java/io/PrintStream.println:(Z)V

注意如何:

  • 03:加载相同ldc #2的常量(文字)
  • 12:创建一个新的字符串实例(#2作为参数)
  • 35:ac作为常规对象与if_acmpne

常量字符串的表示在字节码上非常神奇:

并且上面的 JVMS 引用似乎是说,只要指向的 Utf8 相同,那么相同的实例就会被加载ldc

我对字段进行了类似的测试,并且:

结论:字符串池有直接字节码支持,内存表示高效。

奖励:将其与没有直接字节码支持(即没有模拟)的Integer pool进行比较。CONSTANT_String_info

于 2016-02-12T11:04:09.563 回答
22

Java 8 或以上版本的更新。在 Java 8 中,PermGen(永久代)空间被移除并被 Meta Space 取代。字符串池内存被移动到 JVM 的堆中。

与 Java 7 相比,堆中的字符串池大小有所增加。因此,您有更多空间用于内部化字符串,但您对整个应用程序的内存更少。

还有一件事,你已经知道在Java中比较2个对象(的引用)时,''用于比较==对象的引用,' equals'用于比较对象的内容。

让我们检查一下这段代码:

String value1 = "70";
String value2 = "70";
String value3 = new Integer(70).toString();

结果:

value1 == value2 ---> 真的

value1 == value3 ---> 假的

value1.equals(value3) ---> 真的

value1 == value3.intern()---> 真的

这就是为什么你应该使用 ' equals' 来比较 2 个 String 对象。这intern()就是有用的方式。

于 2018-08-04T10:53:05.930 回答
7

由于字符串是对象,并且由于 Java 中的所有对象始终只存储在堆空间中,因此所有字符串都存储在堆空间中。但是,Java 将不使用 new 关键字创建的字符串保存在堆空间的一个特殊区域中,该区域称为“字符串池”。Java 将使用 new 关键字创建的字符串保存在常规堆空间中。

字符串池的目的是维护一组唯一的字符串。每当您不使用 new 关键字创建新字符串时,Java 都会检查字符串池中是否已存在相同的字符串。如果是,Java 返回对同一个 String 对象的引用,如果不是,Java 在字符串池中创建一个新的 String 对象并返回它的引用。因此,例如,如果您在代码中使用字符串“hello”两次,如下所示,您将获得对同一字符串的引用。我们实际上可以通过使用==运算符比较两个不同的参考变量来测试这个理论,如下面的代码所示:

String str1 = "hello";
String str2 = "hello";
System.out.println(str1 == str2); //prints true

String str3 = new String("hello");
String str4 = new String("hello");

System.out.println(str1 == str3); //prints false
System.out.println(str3 == str4); //prints false 

==运算符只是检查两个引用是否指向同一个对象,如果指向同一个对象,则返回 true。在上面的代码中,str2获取对之前创建的同一个 String 对象的引用。但是,str3str4获得对两个完全不同的 String 对象的引用。这就是为什么str1 == str2返回 true 但str1 == str3str3 == str4返回 false 的原因。事实上,当你做new String("hello");如果这是第一次在程序中的任何地方使用字符串“hello”,则会创建两个 String 对象,而不是仅创建一个 - 一个在字符串池中,因为使用了带引号的字符串,一个在常规堆空间中,因为新关键字的使用。

字符串池是 Java 通过避免创建包含相同值的多个字符串对象来节省程序内存的方法。可以使用 String 的 intern 方法从字符串池中为使用 new 关键字创建的字符串获取字符串。它被称为字符串对象的“实习”。例如,

String str1 = "hello";
String str2 = new String("hello");
String str3 = str2.intern(); //get an interned string obj

System.out.println(str1 == str2); //prints false
System.out.println(str1 == str3); //prints true

OCP Java SE 11 程序员,Deshmukh

于 2020-03-07T19:37:44.000 回答
3

字符串实习是编译器的一种优化技术。如果在一个编译单元中有两个相同的字符串字面量,则生成的代码可确保在程序集中为该字面量的所有实例(用双引号括起来的字符)只创建一个字符串对象。

我来自 C# 背景,所以我可以举一个例子来解释:

object obj = "Int32";
string str1 = "Int32";
string str2 = typeof(int).Name;

以下比较的输出:

Console.WriteLine(obj == str1); // true
Console.WriteLine(str1 == str2); // true    
Console.WriteLine(obj == str2); // false !?

注1:对象通过引用进行比较。

Note2 :typeof(int).Name 是通过反射方法评估的,因此它不会在编译时进行评估。这里这些比较是在编译时进行的。

结果分析: 1) 正确,因为它们都包含相同的文字,因此生成的代码将只有一个引用“Int32”的对象。见注 1

2) true 因为两个值的内容被检查是相同的。

3) FALSE 因为 str2 和 obj 没有相同的文字。见注 2

于 2017-09-24T04:51:15.747 回答
1
Java interning() method basically makes sure that if String object is present in SCP, If yes then it returns that object and if not then creates that objects in SCP and return its references

for eg: String s1=new String("abc");
        String s2="abc";
        String s3="abc";

s1==s2// false, because 1 object of s1 is stored in heap and other in scp(but this objects doesn't have explicit reference) and s2 in scp
s2==s3// true

now if we do intern on s1
s1=s1.intern() 

//JVM checks if there is any string in the pool with value “abc” is present? Since there is a string object in the pool with value “abc”, its reference is returned.
Notice that we are calling s1 = s1.intern(), so the s1 is now referring to the string pool object having value “abc”.
At this point, all the three string objects are referring to the same object in the string pool. Hence s1==s2 is returning true now.
于 2020-05-31T16:59:45.090 回答
0

通过使用堆对象引用,如果我们想要对应的 SCP 对象引用,我们应该使用 intern() 方法。

示例

class InternDemo
{
public static void main(String[] args)
{
String s1=new String("smith");
String s2=s1.intern();
String s3="smith";
System.out.println(s2==s3);//true
}
}

实习生流程图

于 2021-06-11T13:06:31.300 回答