如何在Java中使用toString方法? [英] How to use the toString method in Java?

查看:130
本文介绍了如何在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

这篇关于如何在Java中使用toString方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆