object(equals、hashcode、tostring)objects方法

1.object

package Java0506;

public class Test01 {
    public static void main(String[] args) {
        Object o1 = new Object();
        Object o2 = new Object();

        //==:比较两个对象是否相等(比较内存地址)  equals:没有重写方法之前比较的是内存地址,重写方法之后比较的是内容
        System.out.println(o1.equals(o2));   //false
        System.out.println(o1 == o2);        //false

        //hashCode:将对象转换成整数
        int n1 = o1.hashCode();
        int n2 = o2.hashCode();
        System.out.println(n1);
        System.out.println(n2);

        //toString:将对象转换成字符串
        String s1 = o1.toString();
        String s2 = o2.toString();
        System.out.println(s1);
        System.out.println(s2);

        //类  没有重写方法之前比较的是内存地址,重写方法之后比较的是内容
        Student student = new Student("晓晓",100);
        Student student1 = new Student("晓晓",100);

        System.out.println(student == student1);       //false  
        System.out.println(student.equals(student1));  //false  

        System.out.println(student.toString());
        System.out.println(student1.toString());

        System.out.println(student.hashCode());
        System.out.println(student1.hashCode());
    }
}

2.Objects

package Java0506;
import java.util.Objects;

public class Test01 {
    public static void main(String[] args) {
        Student a = new Student("晓晓", 100);
        Student b = new Student("晓晓", 100);

        //Objects.equals(a,b):判断两个对象是否相等。
        System.out.println(Objects.equals(a, b)); //false

        //Objects.toString(a):返回字符串形式。如果参数为空对象null,则返回字符串“null”。
        System.out.println(Objects.toString(a));

        //Objects.toString(a,"null"):返回字符串形式。如果参数为空,则返回默认值。
        String s=null;
        System.out.println(Objects.toString(s, "0"));

        //Objects.hashCode(a):返回哈希码值。若参数对象为空,则返回整数0。
        System.out.println(Objects.hashCode(a));

        //Objects.isNull(a):判空方法,如果参数为空则返回true。
        System.out.println(Objects.isNull(a));

        //Objects.nonNull(a):判断非空方法,如果参数不为空则返回true。
        System.out.println(Objects.nonNull(a));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值