Java如何重寫object類的equals方法詳解
1.Object類的equals()方法:
比較兩個對象是否是同一個對象,equals() 方法比較兩個對象,是判斷兩個對象引用指向的是同一個對象,即比較 2 個對象的內(nèi)存地址是否相等。是則返回true
Object類是所有類的父類,它的equals方法自然會被所有類繼承,有一個子 類String對equals方法進行了覆蓋(重寫),使其具有了新功能
2.Object類的equals()方法與==沒區(qū)別
Java.lang.String重寫了equals()方法,把equals()方法的判斷變?yōu)榱伺袛嗥渲?/p>
當有特殊需求,如認為屬性相同即為同一對象時,需要重寫equals()

總結:
1.基本數(shù)據(jù)類型數(shù)據(jù)值只能用
2.對于引用數(shù)據(jù)類型,和Object的equals方法是一樣的。(查看源碼)
由于String類對父類Object的equals方法的重寫,導致equals與= =唯一的區(qū)別在于比較對象
例題 :
重寫比較規(guī)則,判斷兩名學員(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;
}
}
測試類進行測試
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));
}
以上程序執(zhí)行結果

到此這篇關于Java如何重寫object類的equals方法的文章就介紹到這了,更多相關Java重寫object類的equals方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
maven項目中<scope>provided</scope>的作用及說明
這篇文章主要介紹了maven項目中<scope>provided</scope>的作用及說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12
Spring boot+mybatis+thymeleaf 實現(xiàn)登錄注冊增刪改查功能的示例代碼
這篇文章主要介紹了Spring boot+mybatis+thymeleaf 實現(xiàn)登錄注冊增刪改查功能的示例代碼,本文通過實例圖文相結合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07

