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?
没有接受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.
你可能混淆char与CharSequence(针对其存在确实是一个构造函数),但是这是两个完全不同的事情.
| 归档时间: |
|
| 查看次数: |
262 次 |
| 最近记录: |