println(引用类型)
首先调用参数为object的重载函数
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
valueOf()
调用toString
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
toString()
调用hashCode方法
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
总结
当对一个底层方法的重写出了错,其上层所有使用该底层方法的方法都会出错。
例如一旦引用类型重写了hasCode方法,那么将在使用toString(),println()
方法时出现错误(当然,如果你也同时重写了上层方法,使得其不在调用hasCode,那么,该方法能够顺利执行)
package week2.day9;
import java.util.HashSet;
import java.util.Set;
/**
* 2020/8/3
* 21:47
* zmx
*/
public class Work12 {
public static void main(String[] args) {
Set<Student> set = new HashSet<Student>();
Student stu1 = new Student();
System.out.println(stu1.toString());
Student stu2 = new Student("“Tom”", 18);
Student stu3 = new Student("“Tom”", 18);
set.add(stu1);
set.add(stu2);
set.add(stu3);
System.out.println(set.size());
}
}
class Student {
int age;
String name;
public Student(){}
public Student(String name, int age){
this.name = name;
this.age = age;
}
public int hashCode(){//null使用hashCode方法,出现空指针异常
return name.hashCode() + age;
}
public boolean equals(Object o){
if (o == null) return false;
if (o == this) return true;
if (o.getClass() != this.getClass()) return false;
Student stu = (Student) o;
if (stu.name.equals(name) && stu.age == age) return true; else return false;
}
}
输出
当使用Student实例对象的toString(object中继承)或者打印stu1时,会调用stu1的hasCode方法。
stu1本身不为空,但其是使用无参构造方法构建的,其name,age分为为默认值null,0,
null使用hashCode方法,出现空指针异常
但如果Student中重写了toString方法,则stu1的toString方法和println均不会出错。
但当add时,依旧会出错,(对HashSet,add时,会调用hasCode与equals)