62,634
社区成员




When the intern method is invoked, if the pool already contains a string equal to this String object as deterined by the equals(Object) method, then the string from the pool is returned. Otherwise, this string objecct is added to the pool and a reference to this String object is returned.
[/quote]
你引用的这段api文档并不能解除3楼的疑惑。因为我也有同样的疑惑。
对intern函数的用法,我通过api是能理解的。
但是StringBuilder对象的toString方法返回的String对象与new String有何区别呢?
它是在常量区中还是在堆中呢?
另外,5楼的链接中提到不同版本有不同的结果,又是如何理解?
When the intern method is invoked, if the pool already contains a string equal to this String object as deterined by the equals(Object) method, then the string from the pool is returned. Otherwise, this string objecct is added to the pool and a reference to this String object is returned.
[/quote]
你引用的这段api文档并不能解除3楼的疑惑。因为我也有同样的疑惑。
对intern函数的用法,我通过api是能理解的。
但是StringBuilder对象的toString方法返回的String对象与new String有何区别呢?
它是在常量区中还是在堆中呢?
另外,5楼的链接中提到不同版本有不同的结果,又是如何理解?
[/quote]
Ok,详细说明下好了,这个方法比较蛋疼!
确实不同版本的jdk是有区别的,大致分为2种。
String str1 = new StringBuilder("hello").append("world").toString();
String str2 = str1.intern();
System.out.println(str1 == str2);
1、JDK <= 1.6时:
JDK1.6及以下时,常量池(好像叫PermGen)是不再Heap上的,是两个不同的区域。对于上面的代码,str1指向Heap,常量池中没有“helloworld”,当调用intern()方法时,发现常量池中没有,就创建一个,并返回该引用(指向常量池的),所以此时str1 != str2。
2、JDK >= 1.7时:
JDK1.7及以上时,常量池移到Heap中(JDK1.8正式移除PermGen),是一个区域。对于上面的代码,str1还是指向Heap,常量池中此时仍然没有“helloworld”,当调用intern()方法时,发现常量池没有,创建,此时就不同了,由于都是在Heap中,常量池发现Heap中有“helloworld”,就把引用直接指向Heap中的“helloworld”(也就是str1),所以此时str1 == str2
When the intern method is invoked, if the pool already contains a string equal to this String object as deterined by the equals(Object) method, then the string from the pool is returned. Otherwise, this string objecct is added to the pool and a reference to this String object is returned.
String a = "hello";
String b = new String("hello");
System.out.println(a == b.intern()); // 输出true
System.out.println(a == b); // 输出false
System.out.println(a == b.intern()); // 输出false
System.out.println(b == b.intern()); // 输出false