简体   繁体   English

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

[英]Conversion from char[] to String using toString()

I have a char []. 我有一个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

Could you please tell me why the difference? 你能告诉我为什么有区别吗?

When I read the javadoc: 当我阅读javadoc时:

String java.lang.Object.toString() 字符串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())

Looks like it depends on implementation. 看起来它取决于实现。 Shouldn't it be advisable to return a readable string instead with the toString() API. 建议不要使用toString()API返回可读的字符串。

Thanks 谢谢

The code: 编码:

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

behaves the same as: 行为与以下内容相同:

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

That's why print x -> [C@42b3b079 . 这就是为什么print x -> [C@42b3b079

If you construct the StringBuffer as: 如果将StringBuffer构造为:

StringBuffer x = new StringBuffer(name);

Then print x -> metafactory . 然后print x -> metafactory

The reason Object.toString() implemented like this is that, as the base of the inheritance chain, it really doesn't know what information of the subclasses should be added to the return value of toString() . 之所以这样实现Object.toString()是因为作为继承链的基础,它实际上不知道应该将哪些子类的信息添加到toString()的返回值中。 So it just output the class name and the hashcode of the object, which can identify the instance, and it's readable in my opinion. 因此,它仅输出对象的类名和哈希码即可识别实例,并且在我看来是可读的。

If you want to output every element of the array, just use the utility method java.util.Arrays.toString(name) . 如果要输出数组的每个元素,只需使用实用程序方法java.util.Arrays.toString(name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM