1. 程式人生 > 其它 >重寫equals方法

重寫equals方法

  • 自定義類的equals方法使用的是object類中的equals方法,此時的equals方法相當於 == ,比較的是物件的地址
  • 我們怎麼樣才能使equals方法比較的是屬性的值是否相等呢? 比如String類比較的就是字串的值是否相等
  • 很簡單,我們只需要在自定義類中重寫equals方法即可。
  • 若屬性為引用資料型別,用equals方法判斷,這個equals方法也是被重寫過的。

 

public class MyDate {
    private int year;
    private int month;
    private int day;

    public MyDate(int
day, int month, int year){ this.day = day; this.month = month; this.year = year; } public boolean equals(Object obj){ if(this == obj){ return true; } if(obj instanceof MyDate){ MyDate md = (MyDate) obj; return
this.year == md.year && this.month == md.month && this.day == md.day; }else{ return false; } } }
public class MyDateTest {
    public static void main(String[] args) {
            MyDate m1 = new MyDate(14, 3, 1976);
            MyDate m2 = new MyDate(14, 3, 1976);
            
if (m1 == m2) { System.out.println("m1==m2"); } else { System.out.println("m1!=m2"); // m1 != m2 } if (m1.equals(m2)) { System.out.println("m1 is equal to m2");// m1 is equal to m2 } else { System.out.println("m1 is not equal to m2"); } } }