Object

更多内容请看我的个人网站

toString

原本作用

  • 返回对象的字符串表示形式
  • 包名类名+@+对象地址值
System.out.println(obj);

也会打印这样的地址值
源码:

public void println(Object x) {  
    String s = String.valueOf(x);  
    if (getClass() == PrintStream.class) {  
        // need to apply String.valueOf again since first invocation  
        // might return null        writeln(String.valueOf(s));  
    } else {  
        synchronized (this) {  
            print(s);  
            newLine();  
        }  
    }  
}



public static String valueOf(Object obj) {  
    return (obj == null) ? "null" : obj.toString();  
}

如果不是null,就会toString

一般重写toString

  • 如果我们打印一个对象的属性值的话,那么重写toString()就行了,在重写方法时,把对象的属性拼接

equals

public static void main(String[] args) {  
    Student s1 = new Student();  
    Student s2 = new Student();  
  
    boolean equals = s1.equals(s2);  
    System.out.println(equals);  
}

//false

重写equals后运行结果为true

@Override  
public boolean equals(Object o) {  
    if (o == null || getClass() != o.getClass()) return false;  
    Student student = (Student) o;  
    return age == student.age && Objects.equals(name, student.name);  
}  
  
@Override  
public int hashCode() {  
    return Objects.hash(name, age);  
}
public static void main(String[] args) {  
    String s = "abc";  
    StringBuilder sb = new StringBuilder("abc");  
    System.out.println(s.equals(sb));  
    System.out.println(sb.equals(s));  
      
    //运行结果  
    //false false  
}

第一个中调用对象是String,先看是不是同一个对象,如果不是字符串,直接返回false
第二个中调用对象时StringBuilder,StringBuilder没有重写equals方法,Object中使用的是==比较两个对象的地址值

clone

重写对象的clone方法

方法会在底层帮我们创建一个对象,并把原对象的数据拷贝过去
细节:

  1. 重写Object中的clone方法
  2. 让Javabean类实现Cloneable
  3. 创建原对象并调用clone就可以了

Objects

equals

可以规避调用者为null的判断

Student s1=null;  
Student s2=new Student();  
  
boolean equals = Objects.equals(s1, s2);  
System.out.println(equals);

//false

isNull

判断对象是否为null,如果为null,返回true

Student s3 = null;  
Student s4 = new Student();  
System.out.println(Objects.isNull(s3));//true  
System.out.println(Objects.isNull(s4));//false

nonNull

System.out.println(Objects.nonNull(s3));//false  
System.out.println(Objects.nonNull(s4));//true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值