String.intern()
前话
其实以前已经被这个东西迷惑了很久的,现在已经是第三次去看,去理解这个东西了,网上很多的答案,但最近终于找到一些非常好的资料,所以自己就写下记录。
Step One
环境:JDK1.7
IDE:IJ
在1.7中运行时常量池已经在head中
code ①
String s1 = "hello world";
那么我们可以通过查看.class文件中,可以看到在.class文件中常量池中有“hello world”这个字符串
当程序执行到这一句的时候,第一步是在当前类的运行时常量池中(String table)中查找,如果在这个表中查找到就返回表中的对象,否则就在运行时常量区中创建一个String对象,然后再String table中添加相应的key/value。其实这个table就是一个hashtable
那么添加之后就是这样
那么当执行下面的语句的时候
String s2 = "Hello world";
那么变量所赋值来源就是hashtable中的value,所以
s1 == s2;//true
Code ②
String s1 = "abc";
s1 = s1 + "gg";
System.out.println(s1.intern());
String s2 = "abcgg";
System.out.println(s1 == s2);
输出:
abcgg
true
先说一下intern这个函数,String.intern(),它会去查询当前类的hashtable中是否有我这个对象的值,如果有就返回table中的value,没有的话就将本身这个对象加到表中,然后返回自己本身这个对象。
String s1 = "abc";
先创建一个”abc”的对象,然后再table中添加这个key/value
s1 = s1 + "gg";
这个+操作符涉及到StringBuilder,这里不说。先创建“gg”这个对象,然后添加到table中,然后s1被赋值,我们只需要知道它,而这个对象是由StringBuilder.toString 产生的(new String()…),字面量是“abcgg”(这里注意的是这个字面量并没有在table中有存档,就是在table中没有这个key/value),只有是“”才会自动的加入到table中
。
System.out.println(s1.intern());
当我们执行String.intern();方法的时候,“abcgg”才会被添加到table中
String s2 = "abcgg";
当我们执行这一句语句的时候,我们会发现“abcgg”在table中,那么我们就会返回对应的value值,所以最后我们执行比较两个变量的地址是否相等的时候就会返回true
Code ③
String s2 = "abcgg";
String s1 = "abc";
s1 = s1 + "gg";
System.out.println(s1.intern());
System.out.println(s1 == s2);
输出:
abcgg
false
这个很容易解释,第一行“abcgg”会在table中存档,第三行代码 s1 = s1 + “gg”;其实是等同于StringBuilder.toString,最终的结果还是会new String ,而当s1调用intern的时候
Code ④
String s1 = new StringBuilder().append("Str").append("ing").toString();
System.out.println(s1.intern() == s1)
String s2 = new StringBuilder().append("jav").append("a").toString();
System.out.println(s2.intern() == s2);
输出:
true
false
在stackoverflow中有相关的问题
http://stackoverflow.com/questions/36063388/why-does-the-string-intern-method-return-two-different-results#comment59773457_36063388
而在
http://www.docjar.com/html/api/com/sun/tools/jdi/SunCommandLineLauncher.java.html
125行中有“java”这个字符串
相关资料
http://www.jianshu.com/p/0d1c003d2ff5
http://hellojava.info/?p=61
http://calvin1978.blogcn.com/articles/string-intern.html
http://tech.meituan.com/in_depth_understanding_string_intern.html