作者TKforce (tkforce)
看板java
标题[问题] string问题
时间Sat Jan 16 23:58:15 2010
public class test02 {
public static void main(String args[])
{
String a = new String("abc");
String b = new String("abc");
String c = "abc";
String d = "abc";
String e = "def";
String f = "abcdef";
String g = c+e;
String h = (c+e).intern();
String i = new String("abc").intern();
System.out.println(a == b); // false
System.out.println(c == d); // true
System.out.println(f == g); // false
System.out.println(f == h); // true
}
}
这是一段在网路上看到关於string pool的范例
我想问的是: 1.第一个true是怎麽来的? 为什麽会指向同一个"abc"?(因为上面创造了两个)
2.里面的g是同时指向"abc"和"def"的位址吗?
3.假设不看这支程式String a = new String("abc") 和 String a = "abc"
的不同在哪?是一个是制造两个物件,另一个只有制造一个?
虽然有爬过文章但是还是不甚了解
拜托各位指教了!!谢谢!!
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.119.135.223
※ 编辑: TKforce 来自: 140.119.135.223 (01/16 23:58)
1F:→ TonyQ:有new的会重新配置空间 , 没有的就是进到 string pool ,下一 01/16 23:59
2F:→ tkcn: 次用到就可以直接从 string pool 拿. 01/17 00:30
3F:→ TKforce:所以用new的不会进到string pool里面罗? 01/17 00:40
4F:推 hilorrk:没有人觉得这推文怪怪的吗XD 01/17 10:35
5F:推 dendrobium:推文接龙吗XD? 01/17 12:54
6F:推 petertc:runtime建立的String除非用intern(),否则都不会记在pool? 01/17 15:42
7F:→ TonyQ:(奇怪,我昨天明明推了一行就忘了回来推了(思)) 01/17 21:52
8F:→ tkcn:哈,我看过了半小时应该是忘了,我还揣摩了一阵子看要怎麽接 01/17 23:17
9F:推 puzi:楼上的大大真有趣XD 01/18 23:35