String h = "hi";
Run Code Online (Sandbox Code Playgroud)
这里我们将字符串h引用到字符串文字hi.JVM有一个字符串文字池来存储字符串文字,所以我们可以重用字符串,因为它们是不可变的...
当我们说出reusable,这个的确切含义是什么时候?我们在谈论这个address吗?是从同一地址evey时间挑选出来的吗?
是的,为了使事情更简单,您可以将其视为从相同地址中选取,但更精确的变量是持有相同的引用 - JVM可用于映射到对象的正确内存地址的标识符(因为对象可以在内存中移动) .
您可以通过以下代码进行测试:
String w1 = "word";
String w2 = "word";
String b = new String("word"); // explicitly created String (by `new` operator)
// won't be placed in string pool automatically
System.out.println(w1 == w2); // true -> variables hold same reference
System.out.println(w1 == b); // false -> variable hold different references,
// so they represent different objects
b = b.intern(); // checks if pool contains this string, if not puts this string in pool,
// then returns reference of string from pool and stores it in `b` variable
System.out.println(w1 == b); // true -> now b holds same reference as w1
Run Code Online (Sandbox Code Playgroud)
小智 8
如果是
String h = "hi";
String i = "hi";
String j = new String("hi");
Run Code Online (Sandbox Code Playgroud)
根据JDK的版本,编译器可以执行所谓的实习,并创建表示字节数据的单个实例,"hi"并在变量引用之间重用它.在最新的规范中,所有String 文字都被插入到Permanent Generation中的String池中.
new在最后一个语句中使用关键字将创建与单独对象完全相同的字节的新实例.
在创建String对象的运行时是不是在字符串池中,除非.intern()叫他们.这通常不需要并且可能导致问题,很少有任何显着的好处.
h == i; // true
h == j; // false
j.intern();
h == j; // true
Run Code Online (Sandbox Code Playgroud)
这意味着如果 20 个对象使用相同的字面量 String:
private String h = "hi";
Run Code Online (Sandbox Code Playgroud)
实际上,所有这些对象都将引用内存中的同一个 String 实例。并且没关系,因为不可能改变 String 的内容,因为它是不可变的。因此,可以在对象之间毫无问题地共享同一实例。