如何在Java中使用toString方法?

如何在Java中使用toString方法?

问题描述:

有人可以向我解释 toString()方法的概念,在 Object 类中定义?它是如何使用的,它的用途是什么?

Can anybody explain to me the concept of the toString() method, defined in the Object class? How is it used, and what is its purpose?

来自 Object.toString() docs:


返回
对象的字符串表示形式。通常,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.

类Object
的toString方法返回一个字符串,该字符串由对象
为实例的类的
名称组成,at-sign字符
` @',以及
对象的哈希码的无符号十六进制
表示。换句话说,这个方法
返回一个等于
的字符串:

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

示例:

String[] mystr ={"a","b","c"};
System.out.println("mystr.toString: " + mystr.toString());

output:- mystr.toString: [Ljava.lang.String;@13aaa14a