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
- 反之 如果不需要查找元素 则不用重写
即使再小的帆也能远航