toString和hashCode都是Object类中的方法,所以每个对象都可以直接调用。
hashCode方法,返回该对象的哈希码值,Object中的实现一般是通过将该对象的内部地址转换成一个整数。
其形式为:
类的全限定名@hashCode方法返回值的十六进制形式
即:
getClass().getName() + "@" + Integer.toHexString(hashCode())
例如:
public class Student{
}
main:
Student s = new Student();
String str1 = s.toString();
String str2 = s.getClass().getName()+"@"+Integer.toHexString(s.hashCode());
System.out.println(str1);
System.out.println(str2);
输出结果:
com.briup.ch06.Student@6084fa6a
com.briup.ch06.Student@6084fa6a
注:我们可以把最后的那个六十进制数字认为是这个对象的内存地址,但是其实并不是真的地址值,而是这个对象的哈希码值,这个哈希码值默认又是通过对象地址值转换过来的一个数字。(如果我们重写了hashCode方法,那这个返回的哈希码值就真的和对象内存地址没有一点关系了)
toString方法,返回该对象的字符串表示。
例如:
Student s = new Student();
//打印引用时,默认调用其所指向对象的toString方法
System.out.println(s);
System.out.println(s.toString());
注:有些时候还是会有一点区别
Student s = null;
//打印null
System.out.println(s);
//运行报错,空指针异常
System.out.println(s.toString());