日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Java之toString()方法详解

發布時間:2024/4/15 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java之toString()方法详解 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Java之toString()方法詳解

Java中?toString()方法在Object類中和Intent類中都有定義,作用類似,但顯示形式有點區別

一、Object類中toString()方法

toString() 是java.lang.Object類的方法 定義:public?String?toString()

源代碼:

?public?String?toString()?{

????????return?getClass().getName()?+?"@"?+?Integer.toHexString(hashCode());

????}

?

public?String?toString?()

添加于?API 級別 1

Returns 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?方法會返回一個“以文本方式表示”此對象的字符串。結果應是一個簡明但易于讀懂的信息表達式。建議所有子類都重寫此方法

Object?類的?toString?方法返回一個字符串,該字符串由類名(對象是該類的一個實例)、at?標記符“@”和此對象哈希碼的無符號十六進制表示組成。換句話說,該方法返回一個字符串,它的值等于:

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

? 返回:該對象的字符串表示形式。

? 說明:

輸出對象時一般會自動調用toString(?)方法把對象轉換為字符串。例如System.out.println(obj),括號里面的?“obj”如果不是String類型的話,而是對象時,就自動調用obj.toString()方法。當然也可以重載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@后面對應的是此對象哈希碼的無符號十六進制表示形式。

二、Intent類中toString()方法

public String toString() {StringBuilder b = new StringBuilder(128);b.append("Intent { ");toShortString(b, true, true, true, false);b.append(" }");return b.toString();//調用Object類中toString方法,實質上,我們可以<span style="font-family:宋體;">通過</span><span style="color: rgb(51, 153, 102);">子類都重寫此方法,根據自己的需要指定返回形式</span> }


總結

以上是生活随笔為你收集整理的Java之toString()方法详解的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。