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方法
返回:
自己本身的字串