3、
class Test { public static void main(String[] args) { String s1 = "123"; String s2 = "123"; if (s1 == s2) { System.out.println("s1==s2"); } else { System.out.println("s1!=s2"); } } } 输出结果:s1==s2
|
4、
class Test { public static void main(String[] args) { String s1 = new String("123"); String s2 = new String("123"); if (s1 == s2) { System.out.println("s1==s2"); } else { System.out.println("s1!=s2"); } } } 结果:s1!=s2
|
5、
class Test { public static void main(String[] args) { String s1 = new String("123"); String s2 = new String("123"); } } Runtime Heap Summary: Test ========================== Runtime Instance List --------------------- Package Class Count Cumulative Count Memory Cumulative Memory ------- ----- ----- ---------------- ------ ----------------- Total 4 (100.0%) 4 (100.0%) 96 (100.0%) 96 (100.0%) java.lang String 3 (75.0%) 3 (75.0%) 72 (75.0%) 72 (75.0%) char[ ] 1 (25.0%) 1 (25.0%) 24 (25.0%) 24 (25.0%)
|
结论:相同字符串常量,即使在不同语句中被引用,其内存是共用的,"123"只生成一个字符数据和一个String对象,两个new String()分别生成了一个对象。
6、
class Test { public static void main(String[] args) { String s1 = new String("123"); String s2 = new String("1234"); } } Runtime Heap Summary: Test ========================== Runtime Instance List --------------------- Package Class Count Cumulative Count Memory Cumulative Memory ------- ----- ----- ---------------- ------ ----------------- Total 6 (100.0%) 6 (100.0%) 144 (100.0%) 144 (100.0%) java.lang String 4 (66.7%) 4 (66.7%) 96 (66.7%) 96 (66.7%) char[ ] 2 (33.3%) 2 (33.3%) 48 (33.3%) 48 (33.3%)
|
结论:"123"和"1234"分别生成了各自的字符数组和String对象。两个new String()分别创建一个String对象。
做了一个测试,
long begin = System.nanoTime();
//String str = "abcdefghijklmnopqrstuvwxyz";
String str1 = new String("abcdefghijklmnopqrstuvwxyz");
long end = System.nanoTime();
System.out.println(end - begin);
|
上一页 [1] [2] [3] 下一页

【责编:Ken】