1. 程式人生 > 實用技巧 >MySQL自帶工具使用介紹

MySQL自帶工具使用介紹

技術標籤:java

1.Object類的equals()方法:
比較兩個物件是否是同一個物件,equals() 方法比較兩個物件,是判斷兩個物件引用指向的是同一個物件,即比較 2 個物件的記憶體地址是否相等。是則返回true
Object類是所有類的父類,它的equals方法自然會被所有類繼承,有一個子 類String對equals方法進行了覆蓋(重寫),使其具有了新功能


2.Object類的equals()方法與==沒區別
Java.lang.String重寫了equals()方法,把equals()方法的判斷變為了判斷其值
當有特殊需求,如認為屬性相同即為同一物件時,需要重寫equals()

在這裡插入圖片描述

總結:
1.基本資料型別資料值只能用
2.對於引用資料型別,和Object的equals方法是一樣的。(檢視原始碼)
由於String類對父類Object的equals方法的重寫,導致equals與= =唯一的區別在於比較物件

例題 :
重寫比較規則,判斷兩名學員(Student)是否為同一物件
Student相關屬性
Id(學號)、name(姓名)、age(年齡)
如果兩名學員的學號以及姓名相同,則為同一物件

在這裡插入圖片描述
1 對 Student類進行封裝 然後在裡面重寫equals方法
方法程式碼:

public class  Student {
    private  int id;
    private  String name;
    private  int age;

    @Override  //重寫equals方法
    public boolean equals(Object obj) {
       if(obj instanceof Student){
           Student s1=(Student)obj;
           return this.id==s1.id&&this.name==s1.name&&this.age==s1.age;
       }else {
           System.out.println("錯誤");
           return false;
       }
    }

    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

測試類進行測試

 public static void main(String[] args) {
        Student s1 = new Student(1,"張三",18);
        Student s2 = new Student(1,"張三",18);

        Student s3 = new Student(1,"張三",18);
        Student s4 = new Student(1,"張三",20);

        System.out.println(s1.equals(s2));

        System.out.println(s3.equals(s4));



    }

以上程式執行結果

在這裡插入圖片描述