StringTable
// jdk1.8
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
private final char[] value;
}
// jdk1.9
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
@Stable
private final byte[] value;
}
字符串拼接操作
new String(“a”) + new String(“b”)创建了几个对象?
- StringBuilder.toString()没有在字符串常量池中存放字面量。
/** 题目:
* new String("ab")会创建几个对象?看字节码,就知道是两个。
* 一个对象是:new关键字在堆空间创建的
* 另一个对象是:字符串常量池中的对象"ab"。 字节码指令:ldc
*
*
* 思考:
* new String("a") + new String("b")呢?
* 对象1:new StringBuilder()
* 对象2: new String("a")
* 对象3: 常量池中的"a"
* 对象4: new String("b")
* 对象5: 常量池中的"b"
*
* 深入剖析: StringBuilder的toString():
* 对象6 :new String("ab")
* 强调一下,toString()的调用,在字符串常量池中,没有生成"ab"
*/
- 在jdk8中,字符串常量池和对象都放在堆中,为了节省空间。当运行s3.intern()时,字符串常量池中直接存放了一个指向堆空间中String(“11”)对象的地址引用。
public class StringIntern {
public static void main(String[] args) {
String s = new String("1");
s.intern();//调用此方法之前,字符串常量池中已经存在了"1"
String s2 = "1";
System.out.println(s == s2);//jdk6:false jdk7/8:false
String s3 = new String("1") + new String("1");//s3变量记录的地址为:new String("11")
//执行完上一行代码以后,字符串常量池中,是否存在"11"呢?
// 答案:不存在!!
s3.intern();//在字符串常量池中生成"11"。
// 如何理解:jdk6:创建了一个新的对象"11",也就有新的地址。
// jdk7:此时常量中并没有创建"11",而是创建一个指向堆空间中new String("11")的地址
String s4 = "11";//s4变量记录的地址:使用的是上一行代码代码执行时,在常量池中生成的"11"的地址
System.out.println(s3 == s4);//jdk6:false jdk7/8:true
}
}
- 新定义一个字符串时,先在字符串常量池中寻找是否存在该字面量或者该字面量的引用。
public class StringIntern1 {
public static void main(String[] args) {
//StringIntern.java中练习的拓展:
String s3 = new String("1") + new String("1");//new String("11")
//执行完上一行代码以后,字符串常量池中,是否存在"11"呢?答案:不存在!!
String s4 = "11";//在字符串常量池中生成对象"11"
String s5 = s3.intern();
System.out.println(s3 == s4);//false s3是对象应用,s4是字面量引用
System.out.println(s5 == s4);//true s5,s4都是字面量引用
}
}
例1:
public class StringExer1 {
public static void main(String[] args) {
// String x = "ab";
String s = new String("a") + new String("b");//new String("ab")
//在上一行代码执行完以后,字符串常量池中并没有"ab"
String s2 = s.intern();//jdk6中:在串池中创建一个字符串"ab"
//jdk8中:串池中没有创建字符串"ab",而是创建一个引用,指向new String("ab"),将此引用返回
System.out.println(s2 == "ab");//jdk6:true jdk8:true
System.out.println(s == "ab");//jdk6:false jdk8:true
}
}
例2:
public class StringExer2 {
public static void main(String[] args) {
String s1 = new String("ab");//执行完以后,会在字符串常量池中会生成"ab"
// String s1 = new String("a") + new String("b");执行完以后,不会在字符串常量池中会生成"ab"
s1.intern();
String s2 = "ab";
System.out.println(s1 == s2); // jdk8: false;
}
}
总结:jdk8中,intern()方法总会往字符串常量池中放一个东西。字面量or引用,然后返回放的这个东西。
开发tips
在面临需要大量存储重复字符串的场景中,通过调用intern()方法,可以提高效率,并降低内存使用量。
String s = String("ab").intern();
在这个过程中,达到的目标只是存储字符串,那么在堆中创建的对象是可以被回收的。