将Char作为参数传递给其重载的构造函数时,StringBuffer的行为如何? [英] How StringBuffer behaves When Passing Char as argument to its Overloaded Constructor?
问题描述
StringBuffer sb = new StringBuffer('A');
System.out.println("sb = " + sb.toString());
sb.append("Hello");
System.out.println("sb = " + sb.toString());
输出:
sb =
sb =
sb =你好
但如果我通过一个字符串而不是字符,它附加到Hello。
为什么这个奇怪的行为有char?
But if i pass a String instead of character, it appends to Hello . Why is this strange behavior with char ?
推荐答案
没有构造函数接受炭
。您最终获得了 <$ c由于Java自动将 char
转换为 int $ c $,$ c> int
构造函数 c>,从而指定初始容量。
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 <code>capacity</code>
* argument is less than <code>0</code>.
*/
public StringBuffer(int capacity) {
super(capacity);
}
Cf。这个最小的例子:
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');
}
}
输出:
97
97
98
98
然而
StringBuffer buf3 = new StringBuffer("a");
System.out.println(buf3.capacity());
结果初始容量 17
。
您可能已将<$ h $ => http://docs.oracle.com/javase与 char
混淆/7/docs/api/java/lang/CharSequence.html\"rel =nofollow> CharSequence
(确实有一个构造函数),但是这是完全不同的两件事。
You might have confused char
with CharSequence
(for which there is indeed a constructor), but these are two completely different things.
这篇关于将Char作为参数传递给其重载的构造函数时,StringBuffer的行为如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!