首页 / 软件开发 / JAVA / Java的toString()方法
Java的toString()方法2013-12-05 51cto sundunjamJava 基础内容toString方法我们处处都用到,是一个很重点的小知识,这里大概讲一下:我们查阅 API文档,查看java.lang.Object类的toString方法的详细描述是这样的:toStringpublic 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方法,看看是否一样呢toStringpublic String toString()This object (which is already a string!) is itself returned.Specified by:toString in interface CharSequenceOverrides:toString in class ObjectReturns:the string itself.我们还是 翻译一下吧:这个对象自己(它已经是一个字符串了)就是返回值说明:CharSequence接口中的toString方法重写:重写了Object中的toString方法返回:自己本身的字符串