引用类型println,toString,hasCode

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)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值