我明白,鉴于字符串的不变性,类似
String a="";
for(int i=0;i++<9;)
a+=i;
效率非常低,因为最初一个字符串被实例化并放入字符串池,然后使用a+=i
创建一个新字符串(0 在第一个循环中),由 a
引用,而前一个现在有资格进行垃圾回收。这种情况发生了九次。
更好的方法是使用 StringBuilder
:
StringBuilder a=new StringBuilder("");
for(int i=0;i++<9;)
a.append(i);
但是当我用
新
关键字?
String a=new String("");
for(int i=0;i++<9;)
a+=i;
我知道在这种情况下 a
不会被驻留(它不在字符串池中),但它仍然是不可变的吗? a+=i
指令此时做了什么?该行为是否与我的第一个示例相同?
最佳答案
只有 String
literals 或调用 intern()
方法的 Strings
被放入 String水池。串联不会自动插入 String
,因此您的示例在字符串池方面将是相同的。
String abc = new String("abc"); //"abc" is put on the pool
abc += "def"; //"def" is put on the pool, but "abcdef" is not
String xyz = "abcdefghi".substring(0, 6).intern(); //"abcdef" is now added to the pool and returned by the intern() function
String xyz = "test"; //test is put on the pool
xyz += "ing"; //ing is put on the pool, but "testing" is not
并对此进行扩展,请注意 String 构造函数不会自动实习(或不实习)字符串。使用字符串文字(代码中引号中的字符串)是导致字符串位于字符串池中的原因。
String abc = "abc"; //"abc" is in the pool
String def = "def"; //"def" is in the pool
String str1 = new String(abc + def); //"abcdef" is not in the pool yet
String str2 = new String("abcdef"); //"abcdef" is on the pool now
另请注意,String
复制构造函数几乎从不使用,因为无论如何字符串都是不可变的。
关于java - 关于字符串连接行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30575709/