在创建对象时如何判断相同类的两个对象相等:
class Person {
private String name;
private String idStr;
public Person() {
}
public Person(String name, String idStr) {
this.name = name;
this.idStr = idStr;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdStr() {
return idStr;
}
public void setIdStr(String idStr) {
this.idStr = idStr;
}
public boolean equals(Object obj) {
//如果两个对象为同一个对象,则相等
if (this == obj)
return true;
//如何obj的对象Person对象,且当前对象的idStr和obj对象的idStr属性相等,则判断为相等。
if (obj != null && obj.getClass() == Person.class) {
Person personObj = (Person) obj;
if (this.getIdStr().equals(personObj.getIdStr())) {
return true;
}
}
return false;
}
}
class OverrideEqualsRight {
public static void main(String[] args) {
Person p1 = new Person("孙悟空", "12343433433");
Person p2 = new Person("孙行者", "12343433433");
Person p3 = new Person("孙悟饭", "99933433");
System.out.println("p1和p2是否相等?" + p1.equals(p2));
System.out.println("p2和p3是否相等?" + p2.equals(p3));
}
}