Puzzle 23: No Pain, No Gain
下面的代码输出什么?
StringBuffer word = new StringBuffer('H');
word.append("ello");
System.out.println(word);
无论执行多少次,都得不到 "Hello",只得到"ello",这是怎么回事呢?改成下面的就好了:
StringBuffer word = new StringBuffer("H");
word.append("ello");
System.out.println(word);
注意上面黑体标识的代码,头一个用的是单引号,后一个用的是双引号。这种写法上的差异,导致了参数类新是不一样的,从而调用了 StringBuffer 不同的构造方法。查 API 文档:
http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
public StringBuffer(int capacity)
Constructs a string buffer with no characters in it and the specified initial capacity.
Parameters:
capacity
- the initial capacity.
Throws:
NegativeArraySizeException
- if the capacity
argument is less than 0
.
public StringBuffer(String str)
Constructs a string buffer initialized to the contents of the specified string. The initial capacity of the string buffer is 16
plus the length of the string argument.
Parameters:
str
- the initial contents of the buffer.
Throws:
NullPointerException
- if str
is null
这下就明了了,第一段代码中new StringBuffer('H')
的 'H' 是 char 类型,被 cast 成 int 后调用构造器 StringBuffer(int capacity) 。第二段代码调用构造器StringBuffer(String str) 。所以出现了本文开头的现象。
值得注意的是,StringBuidler 也有类型的情况。
原书中,还夹带说了 switch 语句块中遗漏 break 的后果,具体代码参: