简单纪要:String的intern()

我们可以先由源码注释来了解intern();

When the intern method is invoked, if the pool already contains a
string equal to this {@code String} object as determined by
the {@link #equals(Object)} method, then the string from the pool is
returned. Otherwise, this {@code String} object is added to the
pool and a reference to this {@code String} object is returned.

简单一句话总结:当常量池中的存在该对象,就返回该对象在常量池中的引用,否则,当常量池中不存在,放到常量池中,再返回改对象的引用;

String t1 = "ABC";
String t2 = new String("ABC");
String t3 = "ABC";
System.out.println(t1 == t2); //false
System.out.println(t1 == t3);//true
System.out.println(t2.intern() == t1); //true   

 

java为了避免产生大量的Sting对象,设计了一个字符串常量池。工作原理是这样的,创建一个字符串时,JVM首先为检查字符串常量池中是否有值相等的字符串,
如果有,则不再创建,直接返回该字符串的引用地址,若没有,则创建,然后放到字符串常量池中,并返回新创建的字符串的引用地址。所以上面 t1 与 t3 引用地址相同

因为t1 是在常量池中,所以t1的引用地址指向常量池的对象, new出来的对象放在堆空间,所以 t2 的引用地址首先会指向 堆空间, 所以 t1 == t2 返回的 false ;
t2的引用地址 首先指向 堆空间,堆空间 会指 向常量池中的一个 字符串,当调用 t2.intern(),会返回该对象在常量池中的引用地址;
 
posted @ 2019-11-28 15:08  爱吃螃蟹的牧羊人  阅读(86)  评论(0编辑  收藏  举报