How StringBuffer behaves When Passing Char as argument to its Overloaded Constructor?

前端 未结 2 1616
心在旅途
心在旅途 2020-12-21 12:12
    StringBuffer sb = new StringBuffer(\'A\');
    System.out.println(\"sb = \" + sb.toString());
    sb.append(\"Hello\");
    System.out.println(\"sb = \" + sb.toS         


        
2条回答
  •  一整个雨季
    2020-12-21 12:43

    There is no constructor which accepts a char. You end up with the int constructor due to Java automatically converting your char to an int, thus specifying the initial capacity.

    /**
     * Constructs a string buffer with no characters in it and
     * the specified initial capacity.
     *
     * @param      capacity  the initial capacity.
     * @exception  NegativeArraySizeException  if the capacity
     *               argument is less than 0.
     */
    public StringBuffer(int capacity) {
        super(capacity);
    }
    

    Cf. this minimal example:

    public class StringBufferTest {
        public static void main(String[] args) {
            StringBuffer buf = new StringBuffer('a');
            System.out.println(buf.capacity());
            System.out.println((int) 'a');
            StringBuffer buf2 = new StringBuffer('b');
            System.out.println(buf2.capacity());
            System.out.println((int) 'b');
        }
    }
    

    Output:

    97
    97
    98
    98
    

    Whereas

    StringBuffer buf3 = new StringBuffer("a");
    System.out.println(buf3.capacity());
    

    Results in an initial capacity of 17.

    You might have confused char with CharSequence (for which there is indeed a constructor), but these are two completely different things.

提交回复
热议问题