更新时间:2023-02-23 09:38:12
当我用new定义一个StringBuffer变量时,该字符串不会添加到字符串池中,对吧?
When I define a StringBuffer variable with new, this string is not added to the String pool, right?
创建 StringBuffer
根本不会创建 String
.
现在,当我定义另一个StringBuffer而不是new时,我突然将其定义为StrPrev.append("XXX").
Now, when I define another StringBuffer but not with new, I define it as StrPrev.append("XXX") suddenly it is.
这是完全困惑的:
调用 strBuff.append("XXX")
时,您未定义新的 StringBuffer
.您正在更新 strBuff
所引用的现有 StringBuffer
.具体来说,您要在缓冲区的末尾添加额外的字符.
When you call strBuff.append("XXX")
you are NOT defining a new StringBuffer
. You are updating the existing StringBuffer
that strBuff
refers to. Specifically, you are adding extra characters to the end of the buffer.
当您调用 strBuff.toString()
时,您只能从 StringBuffer
中获得一个新的 String
.
You only get a new String
from the StringBuffer
when you call strBuff.toString()
.
仅当在 String
上调用 intern()
时,才将 String
添加到字符串池.并且只有在池中没有相等的字符串时,才将字符串添加到池中.
You only add a String
to the string pool when you call intern()
on the String
. And that only adds the string to the pool if there is not already an equal string in the pool.
表示文字"XXX"
的String对象是字符串池的成员.但这是在加载类时发生的(即将String添加到池中),而不是在执行 append
调用时发生.
The String object that represents the literal "XXX"
is a member of the string pool. But that happens (i.e. the String is added to the pool) when the class is loaded, not when you execute the append
call.
((如果您的老师告诉您StringBuffer将字符串放入Java字符串池中,那么他/她是错误的.但是,由于您的描述很乱,我怀疑您实际上误会了或误解了老师真的说过.)
(If you teacher told you that StringBuffer puts strings into the Java string pool, he / she is wrong. But, given your rather garbled description, I suspect that you actually misheard or misunderstood what your teacher really said.)