歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java數組不能通過toString方法轉為字符串

Java數組不能通過toString方法轉為字符串

日期:2017/3/1 9:36:40   编辑:Linux編程

Java裡,所有的類,不管是Java庫裡面的類,或者是你自己創建的類,全部是從object這個類繼承的。object裡有一個方法就是toString(),那麼所有的類創建的時候,都有一個toString的方法。

這個方法是干什麼的呢?

首先我們得了解,Java輸出用的函數print();是不接受對象直接輸出的,只接受字符串或者數字之類的輸出。那麼你想把一個創建好的對象拿來輸出怎麼辦?例如:

package com.spring.h3;

public class Test2 {
public static void main(String[] args) {
System.out.println("new Test2()==="+new Test2());
//輸出結果為:new Test2()===com.spring.h3.Test2@18a992f
}
}

按照print接受的類型來說,s1是不能直接輸出的,那麼是否代表這個是不能編譯運行的呢?當然不是。因為當print檢測到輸出的是一個對象而不是字符或者數字時,那麼它會去調用這個對象類裡面的toString 方法,輸出結果為[類型@哈希值]。Object類中的toString()方法的源代碼如下:

/**
* Returns a string representation of the object. In general, the
* <code>toString</code> 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.
* <p>
* The <code>toString</code> method for class <code>Object</code>
* returns a string consisting of the name of the class of which the
* object is an instance, the at-sign character `<code>@</code>', 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:
* <blockquote>
* <pre>
* getClass().getName() + '@' + Integer.toHexString(hashCode())
* </pre></blockquote>
*
* @return a string representation of the object.
*/
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

而數組類中並沒有對此方法重寫(override),僅僅是重載(overload)為類的靜態方法(參見java.util.Arrays)。所以,數組直接使用toString()的結果也是[類型@哈希值]。

  所以數組轉為字符串應寫成:

Arrays.toString(a) 

  這種方法的toString()是帶格式的,也就是說輸出的是[a, b, c],如果僅僅想輸出abc則需用以下兩種方法:

  方法1:直接在構造String時轉換。

char[] data = {'a', 'b', 'c'};

String str = new String(data);

  方法2:調用String類的方法轉換。

String.valueOf(char[] ch)

Copyright © Linux教程網 All Rights Reserved