4

我的问题是我是否使用 StringBuffer(或 StringBuilder)以及我是否多次在实例上调用 toString 方法。StringBuffer 每次都会返回新的 String 实例还是从 String 池返回 String?(假设我在两次调用之间没有对 StringBuffer 进行任何更改)

4

3 回答 3

5

As per docs of toString() of StringBuffer

Converts to a string representing the data in this string buffer. A new String object is allocated and initialized to contain the character sequence currently represented by this string buffer. This String is then returned. Subsequent changes to the string buffer do not affect the contents of the String.

So, A new String object is allocated and initialized.

String objects allocated via new operator are stored in the heap, and there is no sharing of storage for the same contents, where as String literals are stored in a common pool.

String s1 = "Hello";              // String literal
String s2 = "Hello";              // String literal
String s3 = s1;                   // same reference
String s4 = new String("Hello");  // String object
String s5 = new String("Hello");  // String object

where s1 == s2 == s3 but s4 != s5

于 2013-07-18T10:30:02.797 回答
4

只有字符串文字被放置在字符串常量池中。例如String s = "abc";将在字符串池中,而String s = new String("abc")不会。toString()方法创建了一个新字符串,因此返回的字符串不会来自文字池。

每当toString()遇到方法时,都会创建一个新的字符串。

仅当您执行以下操作时,才会再次引用字符串常量池对象。

String s = "abc";
String s1 = "abc";

这意味着两个引用变量ss1将引用常量池中的相同abc文字。

您可以在此处找到有关字符串常量池的有用文章。http://www.thejavageek.com/2013/06/19/the-string-constant-pool/

于 2013-07-18T10:27:53.290 回答
1

Yes calling toString method of StringBuffer and StringBuilder will create a new string object everytime as these methods use the new keyword to return a string.

Here is the code for toString from StringBuffer class:

  public synchronized String toString() {
        return new String(value, 0, count);
    }

Here is the toString method from StringBuilder class:

public String toString() {
        // Create a copy, don't share the array
        return new String(value, 0, count);
    }
于 2013-07-18T10:29:30.933 回答