School類
package com.collection.equals;
/*
* 定義一個學校類 相當于一個學校模闆
* 狀态: 1.學校id 2.學校名稱
* */
public class School {
private int id;
private String name;
public School(int id, String name) {
this.id = id;
this.name = name;
}
public School() {
}
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;
}
}
前面也提到過 == 和equals的差別
具體連結:== 和 equals差別
直接指派方式:建立的對象存放在字元串對象池裡 如果再建立一個一模一樣的 不會再建立
執行個體化方式: 每次建立都會配置設定一個新的記憶體空間出來
System.out.println(list.contains(new School(1,"上海交大")));
School school1 = new School(1, "上海交大");
School school2 = new School(1, "上海交大");
System.out.println(school1.equals(school2));
System.out.println(school1 == school2);
/*
* System.out.println(school1.equals(school2)); 傳回值 false
* System.out.println(school1 == school2); 傳回值 false
* 因為 每次執行個體化建立都會配置設定一個新的記憶體空間出來 哪怕資料是一模一樣
* 在記憶體中的位址都是不同的
* */
list接口中的contains方法
package com.collection.equals;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/*
* list 接口
* 重寫equals方法
* */
public class ListEquals {
@Test
public void test() {
// 1. 定義一個list對象
List list = new ArrayList();
// 2. 添加資料
list.add(123);
list.add(345);
list.add(666);
list.add(new School(1, "上海交大"));
// 3. contains方法判斷
System.out.println(list.contains(new School(1, "上海交大")));
/*
* System.out.println(list.contains(new School(1,"上海交大"))); 傳回值 false
* 因為 ArrayList 類中 contains 方法 通過 equals 方法來判斷是否相等
* o相當于 new School(1,"上海交大")
* lementData[i] 則是 list中每一個元素
* o.equals(elementData[i])
* */
}
}
ArrayList源碼contains方法
由上可以看出 當調用
list.contains(new School(1,"上海交大"))
實際比較的是Object類中 equals()方法 前提是 子類沒有重寫equals方法 否則就是調用自身的
public boolean equals(Object obj) {
return (this == obj);
}
由上可以看出 Object的equals方法 内部判斷
return this == obj
this
是調用目前函數的對象
obj
就是形參
如果循環周遊到了list中的new School(1, "上海交大")這一項 與 new School(1, "上海交大") 進行equals
對比 其實就跟上面例子表述的一樣
傳回值false
因為 new了兩次 每次執行個體化都會有一個新的位址值
是以 如果是自定義類 必須要重寫 equals方法
School重寫equals方法
public class School {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
School school = (School) o;
if (id != school.id) return false;
return name != null ? name.equals(school.name) : school.name == null;
}
}
再次執行contains方法 傳回true
小結
- 如果在
中查找元素 自定義類必須正确的重寫 equals方法 Java标準庫提供的String、Integer等已經覆寫了equals()方法List
- 反之 如果不需要查找元素 則不用重寫
即使再小的帆也能遠航