将Char作为参数传递给其重载的构造函数时,StringBuffer的行为如何?

jit*_*tan 2 java

    StringBuffer sb = new StringBuffer('A');
    System.out.println("sb = " + sb.toString());
    sb.append("Hello");
    System.out.println("sb = " + sb.toString());
Run Code Online (Sandbox Code Playgroud)

输出:

sb =

sb =你好

但是,如果我传递一个字符串而不是字符,它会附加到Hello.为什么这个奇怪的行为与char?

Mar*_*vin 6

没有接受a的构造函数char.由于Java会自动将您转换为a ,因此您最终会使用int构造函数,从而指定初始容量.charint

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

参看 这个最小的例子:

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

97
97
98
98
Run Code Online (Sandbox Code Playgroud)

StringBuffer buf3 = new StringBuffer("a");
System.out.println(buf3.capacity());
Run Code Online (Sandbox Code Playgroud)

结果初始容量为17.

你可能混淆charCharSequence(针对其存在确实是一个构造函数),但是这是两个完全不同的事情.