1.Object类的equals方法(源码)
public boolean equals(Object obj) {
return (this == obj);//判断如果比较的两个对象是同一个对象,则返回true
}
2.String类重写Object类的equals方法(源码)
public boolean equals(Object anObject) {
//判断如果比较的两个对象是同一个对象,则直接返回true
if (this == anObject) {
return true;
}
if (anObject instanceof String) { //类型判断,是String类才比较
String anotherString = (String)anObject;//向下转型,需要得到anObject的属性
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
3.Integer类重写Object类的equals方法(源码)
public boolean equals(Object obj) {
if (obj instanceof Integer) { //判断obj是不是Integer类,是才比较
return value == ((Integer)obj).intValue();//向下转型,如果值相等就返回true
}
return false;
}
4.自写equals方法
自定义Person类(并在Person类中重写Object类的equals方法):
package oop.demo07;
public class Person {
private String name;
private int age;
private char gender;
public Person() {
}
public Person(String name, int age, char gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
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 char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof Person) {
Person p = (Person) obj;
return this.name.equals(p.name) && this.age == p.age && this.gender == p.gender;
}
return false;
}
}
定义测试类:
package oop.demo07;
public class EqualsTest {
public static void main(String[] args) {
Person person1 = new Person("zs",22,'男');
Person person2 = new Person("zs",22,'男');
Person person3 = new Person("lisi",22,'男');
System.out.println(person1.equals(person2));
System.out.println(person1.equals(person3));
}
}
结果: