将Char作为参数传递给其重载的构造函数时,StringBuffer的行为如何?
StringBuffer sb = new StringBuffer('A'); System.out.println("sb = " + sb.toString()); sb.append("Hello"); System.out.println("sb = " + sb.toString());
输出:
sb =
sb =你好
但是,如果我传递一个字符串而不是字符,它会附加到Hello。 为什么这个奇怪的行为与char?
没有接受char
构造函数。 由于Java自动将您的char
转换为int
,因此最终使用int
构造函数 ,从而指定初始容量。
/** * 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 than0
. */ public StringBuffer(int capacity) { super(capacity); }
参看 这个最小的例子:
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'); } }
输出:
97 97 98 98
而
StringBuffer buf3 = new StringBuffer("a"); System.out.println(buf3.capacity());
结果初始容量为17
。
你可能会将char
与CharSequence
混淆(确实有一个构造函数),但这些是两个完全不同的东西。
你使用了下面提到的构造函数。
public StringBuffer(int capacity)
构造一个字符串缓冲区,其中没有字符和指定的初始容量。
参数:capacity – 初始容量。
看到java doc你没有任何带有char输入参数的构造函数。