Java之toString()方法详解
Java之toString()方法詳解
Java中?toString()方法在Object類中和Intent類中都有定義,作用類似,但顯示形式有點區(qū)別
一、Object類中toString()方法
toString() 是java.lang.Object類的方法 定義:public?String?toString()
源代碼:
| ?public?String?toString()?{ ????????return?getClass().getName()?+?"@"?+?Integer.toHexString(hashCode()); ????} |
?
public?String?toString?()
添加于?API 級別 1Returns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. The default implementation is equivalent to the following expression:
getClass().getName() + '@' + Integer.toHexString(hashCode())See?Writing a useful?toString?method?if you intend implementing your own?toString?method.
返回值
- a printable representation of this object.
返回該對象的字符串表示。通常,toString?方法會返回一個“以文本方式表示”此對象的字符串。結(jié)果應(yīng)是一個簡明但易于讀懂的信息表達(dá)式。建議所有子類都重寫此方法。
Object?類的?toString?方法返回一個字符串,該字符串由類名(對象是該類的一個實例)、at?標(biāo)記符“@”和此對象哈希碼的無符號十六進(jìn)制表示組成。換句話說,該方法返回一個字符串,它的值等于:
getClass().getName()?+?'@'?+?Integer.toHexString(hashCode())
? 返回:該對象的字符串表示形式。
? 說明:
輸出對象時一般會自動調(diào)用toString(?)方法把對象轉(zhuǎn)換為字符串。例如System.out.println(obj),括號里面的?“obj”如果不是String類型的話,而是對象時,就自動調(diào)用obj.toString()方法。當(dāng)然也可以重載toString(?)方法,指定返回的形式。
public class Text01 {public static class A{public String toString(){return "this is A";//指定返回的形式}}public static void main(String[] args){A obj = new A();System.out.println(obj);//等同于 System.out.println(obj.toString( ));} }| 輸出:this?is?A 如果把?toString()注釋掉,那么得到:Demo@ed5ba6,其中getClass().getName()返回值為Demo,@后面對應(yīng)的是此對象哈希碼的無符號十六進(jìn)制表示形式。 |
二、Intent類中toString()方法
public String toString() {StringBuilder b = new StringBuilder(128);b.append("Intent { ");toShortString(b, true, true, true, false);b.append(" }");return b.toString();//調(diào)用Object類中toString方法,實質(zhì)上,我們可以<span style="font-family:宋體;">通過</span><span style="color: rgb(51, 153, 102);">子類都重寫此方法,根據(jù)自己的需要指定返回形式</span> }總結(jié)
以上是生活随笔為你收集整理的Java之toString()方法详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: startActivity( ) 与st
- 下一篇: android颜色值的表示方法andro