1、
该方法是将字符串加入到字符串常量池中的方法。
2、基于jdk1.7 inter()分析
String s1 = new String("1") + new String("1");
s1.intern();
String s2 = "11";
System.out.println(s1 == s2) //true
这个程序的运行结果是true。
分析:
1. String s1 = new String("1") + new String("1");
栈中存着s1变量。堆中有3个对象,new String("1")、new String("1")和两个拼接后生成的对象("11")。常量池中有一个对象("1")。s1指向堆中的("11")。
2. s1.intern()
首先判断字符串常量池中是否有对象"11"。如果有,则什么事都不干。如果没有,则在字符串常量池中添加一个堆上"11"的引用。假设这个引用叫p,p = s.intern(),p和s指向的是堆中的同一个对象,p = s
3. String s2 = "11"
去常量池找"11"对象,发现P指向的对象是"11",那么s2也指向堆中的"11"。所以 s1 == s2,因为它们都指向堆中对象"11"。
IMG_20190906_092252.jpg








网友评论