我知道在Java中有两种创建字符串的方式:
String a = "aaa";
String b = new String("bbb");
使用第一种方法,Java会在字符串池中创建一个String对象,并使“a”引用它。(假设“aaa”之前不在池中。)
使用第二种方法,将在堆中创建一个对象,但是JVM是否也会在字符串池中创建一个对象?
在这篇文章Questions about Java's String pool中,@Jesper说:
如果这是真的,那么每次使用If you do this:
String s = new String("abc");
then there will be one String object in the pool, the one that represents the literal "abc", > and there will be a separate String object, not in the pool, that contains a copy of the > content of the pooled object.
new String("bbb");
都会在池中创建一个对象"bbb",也就是说无论以上哪种方式,Java 都将在池中创建一个字符串对象。那么intern()
有什么用呢?在文档中写道:
这意味着有些情况下字符串不在池中,这可能吗?哪个是真的?当调用 intern 方法时,如果池中已经包含一个与此String对象相等(由equals(Object)方法确定)的字符串,则返回池中的字符串。否则,将此String对象添加到池中,并返回对此String对象的引用。