我想问一个关于在Java中使用equals方法测试对象相等性的问题。
我是Java的初学者,目前正在阅读《Java 9合1》Dummies书籍。
我编写了以下代码来检查两个Employee
对象的相等性:
public class TestEquality2 {
public static void main (String [] args) {
Employee emp1 = new Employee ("Martinez", "Anthony");
Employee emp2 = new Employee ("Martinez", "Anthony");
if (emp1.equals(emp2))
System.out.println("These employees are the same");
else
System.out.println("These employees are different.");
}
}
class Employee {
private String firstName;
private String lastName;
public Employee (String firstName, String lastName) {
this.lastName = lastName;
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public String getFirstName() {
return this.firstName;
}
public boolean equals (Object obj) {
// an object must equal itself
if (this == obj)
return true;
// no object equals null
if (this == null)
return false;
if (this.getClass() != obj.getClass())
return false;
// Cast to an employee, then compare the fields
Employee emp = (Employee) obj;
// is this the string's equals method?
return this.lastName.equals(emp.getLastName()) && this.firstName.equals(emp.getFirstName());
}
}
涉及的代码行是equals(Object obj)
方法中的最后一行。
根据代码,我已经重写了默认的 Object equals()
方法并提供了自己的设计,但这里我感到困惑:
return this.lastName.equals(emp.getLastName()) && this.firstName.equals(emp.getFirstName());
我知道lastName
是一个字符串,但我正在使用的equals()
方法,是针对String
的equals()
方法还是我刚刚定义的方法?如果是后者,我知道会创建一个递归情况,尽管我相信我正在使用String equals()
,但为了完整起见,我想澄清一下。
if (this == null)
是无意义的。你是否想表达的是if (obj == null)
? - ernest_kif(this==null) return true
,但我怀疑它应该是if(obj==null) return true
- 感谢您的澄清!既然您已经确认了,我会进行更新! - bodn19888if(this==null)
为真,那么在方法执行之前必然会导致NullPointerException
。而if(obj==null)
应该返回 **false
**,而不是true
。 - ernest_k