StringBuffer何时将字符串添加到字符串池? [英] When does StringBuffer adds strings to the String Pool?

查看:71
本文介绍了StringBuffer何时将字符串添加到字符串池?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 new 定义 StringBuffer 变量时,该字符串不会添加到字符串池中,对吧?

When I define a StringBuffer variable with new, this string is not added to the String pool, right?

现在,当我定义另一个 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.(or so says my college teacher). Why is that? What makes this string to suddenly become a string-pool string?

推荐答案

当我用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.)

这篇关于StringBuffer何时将字符串添加到字符串池?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆