Java的toString()方法

來源:互聯網
上載者:User

Java 基礎內容

toString方法我們處處都用到,是一個很重點的小知識,這裡大概講一下:

我們查閱 API文檔,查看java.lang.Object類的toString方法的詳細描述是這樣的:

toString

public String 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())

Returns:

a string representation of the object.

我們大概翻譯一下:

返回一個能夠代表這個對象的字串。一般而言,toString方法返回這個 對象的“文本運算式”。這個返回的結果很簡潔但是不是易於人們閱讀的資訊運算式。這裡推薦大家在使用的 子類的時候重寫該方法。

對於Object這個類而言,toString方法傳回值是由所屬類的類名、一個“@” 符號和這個對象雜湊碼的無符號十六進位運算式組成的。換句話說,這個方法返回的字串等同於下面的方法 返回的值:

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

返回:

   這個對象的字串運算式

我們再看看java.lang.String類中的 toString方法,看看是否一樣呢

toString

public String toString()

This object (which is already a string!) is itself returned.

Specified by:

toString in interface CharSequence

Overrides:

toString in class Object

Returns:

the string itself.

我們還是 翻譯一下吧:

這個對象自己(它已經是一個字串了)就是傳回值

說明:

CharSequence介面中的toString方法

重寫:

重寫了Object中的toString方法

返回:

自己本身的字串

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.