Java之toString()方法详解
2015-07-18 11:47
726 查看
Java之toString()方法详解
Java中 toString()方法在Object类中和Intent类中都有定义,作用类似,但显示形式有点区别
[title3]一、Object类中toString()方法[/title3]
toString() 是java.lang.Object类的方法
定义:public String toString()
源代码:
public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); } |
public String toString ()
添加于 API 级别 1Returns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's
type and data. The default implementation is equivalent to the following expression:
getClass().getName() + '@' + Integer.toHexString(hashCode())
See Writing a useful
toStringmethod if
you intend implementing your own
toStringmethod.
返回值
a printable representation of this object.
返回该对象的字符串表示。通常,toString 方法会返回一个“以文本方式表示”此对象的字符串。结果应是一个简明但易于读懂的信息表达式。建议所有子类都重写此方法。
Object 类的 toString 方法返回一个字符串,该字符串由类名(对象是该类的一个实例)、at 标记符“@”和此对象哈希码的无符号十六进制表示组成。换句话说,该方法返回一个字符串,它的值等于:
getClass().getName() + '@' + Integer.toHexString(hashCode())
返回:该对象的字符串表示形式。
说明:
输出对象时一般会自动调用toString( )方法把对象转换为字符串。例如System.out.println(obj),括号里面的 “obj”如果不是String类型的话,而是对象时,就自动调用obj.toString()方法。当然也可以重载toString( )方法,指定返回的形式。
public class Text01 { public static class A { public String toString() { return "this is A";//指定返回的形式 } } public static void main(String[] args) { A obj = new A(); System.out.println(obj);//等同于 System.out.println(obj.toString( )); } }
输出:this is A 如果把 toString()注释掉,那么得到:Demo@ed5ba6,其中getClass().getName()返回值为Demo,@后面对应的是此对象哈希码的无符号十六进制表示形式。 |
二、Intent类中toString()方法
public String toString() { StringBuilder b = new StringBuilder(128); b.append("Intent { "); toShortString(b, true, true, true, false); b.append(" }"); return b.toString();//调用Object类中toString方法,实质上,我们可以<span style="font-family:宋体;">通过</span><span style="color: rgb(51, 153, 102);">子类都重写此方法,根据自己的需要指定返回形式</span> }
相关文章推荐
- java并发编程——共享资源的操作
- java新手笔记3 运算符&循环
- struts2 JSON 插件的使用
- java.util.ResourceBundle的用法及报错
- Head First Java资源
- Java Web框架
- 【并发编程】JMM:java内存模型抽象
- 7月18日Java基础:本人为新手正在学习Java中把每天学的东西晚上都会在博客记录希望大神可以指点 不足在此谢过。
- Java中native关键字
- java.sql.SQLException: Could not retrieve transation read-only status server
- [LeetCode][Java] Subsets
- JavaStuNote 4
- Struts2核心(4)——登录问题
- 从[java.lang.OutOfMemoryError: Java heap space]恢复
- [转] 解决windows下eclipse中android项目关联android library project失败问题
- java中数组的初始化和基本排序算法
- Java数据库连接(JDBC)之一:JDBC详细连接过程
- Eclipse和MyEclipse的区别
- java自定义注解
- java自定义注解