Welcome 微信登录

首页 / 软件开发 / JAVA / Java的toString()方法

Java的toString()方法2013-12-05 51cto sundunjamJava 基础内容

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方法

返回:

自己本身的字符串