本帖最后由 黑马张英涛 于 2013-1-20 11:14 编辑
你们看文档不够仔细呦, StringBuffer可以存放任何类型啊,但是,他存放的不是对象的实体,而是通过调用对象类的toString()方法得到的对象的字符串形式,然后将这个字符串存放在容器中,举个简单的例子:- public class MyTest {
- public static void main(String[] args){
- StringBuffer sb = new StringBuffer();
- Person p = new Person();
- System.out.println(sb.append(p));
- }
- }
- class Person {
- @Override
- public String toString() {
- return "person";
- }
- }
复制代码 文档上说的很清楚啊,看这个方法:
append
public StringBuffer append(Object obj)
Appends the string representation of the Object argument.
The argument is converted to a string as if by the method String.valueOf, and the characters of that string are then appended to this sequence.
参数:obj - an Object.
返回:a reference to this object.
另请参见:String.valueOf(java.lang.Object), append(java.lang.String)
他内部调用了String.valueOf(java.lang.Object)方法,而这个方法返回的就是obj.toString()。 |