自定义equals,实现自定义的判断两个类是否相等
/**
*
* @author ligy
*
*/
public class Test1 {
public static void main(String[] args) {
Person p1 = new Person("小明", 23);
Person p2 = new Person("小明", 24);
System.out.println(p1.equals(p2));
}
}
/**
* 一个自己的类
* @author ligy
*
*/
class Person {
private String name;
private int age;
public Person() {}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Person)) {
throw new IllegalArgumentException("传入的参数不是Person类型");
}
Person otherPerson = (Person) obj;
return this.name == otherPerson.name;
}
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;
}
}