使用toString()从char []转换为String

时间:2014-01-26 06:48:18

标签: java string unicode

我有一个char []。

StringBuffer x = new StringBuffer(name.toString());
StringBuffer y = new StringBuffer();
y.append(name);
String s1 = new String(name);

print x -> [C@42b3b079
print y -> metafactory
print s1 -> metafactory
你可以告诉我为什么会有区别吗?

当我阅读javadoc时:

String java.lang.Object.toString()

Returns a string representation of the object. In general, the toString method 
returns    a string that "textually represents" this object. The result should be a   
concise but informative representation that is easy for a person to read. It is 
recommended that all subclasses override this method. 


The toString method for class Object returns a string consisting of the name of the   
class of which the object is an instance, the at-sign character `@', and the unsigned 
hexadecimal representation of the hash code of the object. In other words, this method 
returns a string equal to the value of:

                 getClass().getName() + '@' + Integer.toHexString(hashCode())

看起来它取决于实施。不应该建议退回一个 可读字符串,而不是toString()API。

由于

1 个答案:

答案 0 :(得分:0)

代码:

StringBuffer x = new StringBuffer(name.toString());

的行为与:

相同
String name2str = name.toString(); //here the value of name2str is "[C@42b3b079"
StringBuffer x = new StringBuffer(name2str);

这就是为什么print x -> [C@42b3b079

如果将StringBuffer构造为:

StringBuffer x = new StringBuffer(name);

然后print x -> metafactory

Object.toString()这样实现的原因是,作为继承链的基础,它实际上不知道应该将哪些子类信息添加到toString()的返回值。所以它只输出对象的类名和哈希码,它可以识别实例,在我看来它是可读的。

如果要输出数组的每个元素,只需使用实用程序方法java.util.Arrays.toString(name)