2014-01-26 32 views
0

我有一個char []。使用toString()從char []轉換爲String

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

print x -> [[email protected] 
print y -> metafactory 
print s1 -> metafactory 

你能告訴我爲什麼區別?

當我讀到的Javadoc:

字符串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返回一個 可讀字符串。

感謝

+0

什麼類型的對象是名字? –

+0

我不認爲你應該質疑語言設計。恐怕「對這個問題的回答幾乎完全基於意見,而不是事實,參考或具體的專業知識。」 –

+0

@javaseeker'char []',看來 –

回答

0

代碼:

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

行爲一樣:

String name2str = name.toString(); //here the value of name2str is "[[email protected]" 
StringBuffer x = new StringBuffer(name2str); 

這就是爲什麼print x -> [[email protected]

如果您構建的StringBuffer爲:

StringBuffer x = new StringBuffer(name); 

然後print x -> metafactory

原因Object.toString()像這樣實現的是,作爲繼承鏈的基礎,它真的不知道子類的哪些信息應該被添加到返回值toString()。所以它只輸出對象的類名和哈希碼,它可以識別實例,並且在我看來它是可讀的。

如果要輸出數組的每個元素,只需使用實用程序方法java.util.Arrays.toString(name)