【java学习笔记3】重写Object类的equals()方法的原因和形式

先来看第一段代码:

以下代码是比较两个变量值是否相等!

package chapter03;

public class Test01 {

    public static void main(String[] args) {

        int a = 100;
        int b = 100;
        System.out.println(a == b);
    }
}

 

再来试下Object类的equals()方法:

package chapter03;

public class Test02 {

    public static void main(String[] args) {

        MyAge m1 = new MyAge(1,18);
        MyAge m2 = new MyAge(1,18);
        System.out.println(m1 == m2);

        System.out.println("=======================================");
        System.out.println(m1.equals(m2));
    }

    static class MyAge{

        int id;
        int age;

        public MyAge(){

        }

        public MyAge(int id,int age){
            this.id = id;
            this.age = age;
        }

    }

}

执行结果是:

false
=======================================
false

再看下源码:

    public boolean equals(Object obj) {
        return (this == obj);
    }

很显然,Object类默认的equals()方法不满足需求。

判断两个java对象是否相等,不能使用"==",因为"=="比较的是两个对象的内存地址!

因此需要重写equals()方法!

 

下面是用IDEA开发工具自动生成的equals()方法:

package chapter03;

public class MyTime {

    private int year;
    private int month;
    private int day;

    public MyTime() {
    }

    public MyTime(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    @Override
    public String toString() {
        return "MyTime{" +
                "year=" + year +
                ", month=" + month +
                ", day=" + day +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MyTime myTime = (MyTime) o;
        return year == myTime.year &&
                month == myTime.month &&
                day == myTime.day;
    }


}

如果自己重写方法时,要注意:相同的返回值类型、相同的方法名、相同的形式参数列表!

 

posted @ 2020-12-24 08:50  愚人李愚  阅读(155)  评论(0编辑  收藏  举报