Java字符串池

1. String类的两个构造方法

private final char value[];
private int hash;

public String() {
    this.value = "".value;
}
public String(String original) { this.value = original.value; this.hash = original.hash; }

2. new String中建立几个String对象?

1)建立两个String对象

public static void main(String[] args) {
    String y = new String("hello");
}

内存模型以下:java

2)建立一个String对象

public static void main(String[] args) {
    String x = "hello";
    String y = new String("hello");
}

内存模型以下:this

3. String的intern方法

String类私有地维护着一个初始为空的字符串池,当调用intern方法时:spa

1. 若字符串池中已包含一个等于此String对象的字符串(用 equals方法肯定),则返回池中的字符串。
2. 不然,将此String对象添加到字符串池中,并返回池中的字符串。code

public native String intern();

字符串池中存放的是String对象的引用,而非String对象自己。对象

实验:blog

public static void main(String[] args) {
    String x = "hel";
    x += "lo";
    String y = "ja";
    y += "va";
    System.out.println(x == x.intern()); // true
    System.out.println(y == y.intern()); // false
}

结论:字符串池中已包含一个等于"java"的字符串(JVM启动后在字符串池中加载的字符串还包括:"true"、"false"...)内存

内存模型以下:字符串

intern()前hash

intern()后io

4. 后记

相关文章
相关标签/搜索