public boolean equals(Object otherObject)
{
// a quick test to see if the objects are identical
if (this == otherObject) return true;
// must return false if the explicit parameter is null
if (otherObject == null) return false;
// if the classes don't match, they can't be equal
if (getClass() != otherObject.getClass()) return false;
// now we know otherObject is a non-null Employee
Employee other = (Employee) otherObject;
// test whether the fields have identical values
return name.equals(other.name) && salary == other.salary && hireDay.equals(other.hireDay);
}
为了防备name和hireDay可能为null的情况,需要使用Objects.equals方法.如果两个参数是null,Objects.equals(a,b)调用将返回ture; 如果其中一个参数为null, 则返回false;否则,如果两个参数都不为null,则调用a.equals(b).
对上述程序,有以下问题:
1. 以我目前对于方法和类的理解, public boolean equals(Object otherObject),返回的是一个布尔类型的,括号里面是声明一个otherObject, 这个Objects.equals(a,b)是哪儿来的, 不符合 public boolean equals(Object otherObject) 类型.
- 上述一段话中,还提到了Objects.equals(a,b) 对于判断参数是否是null的情况. 这个方法是怎么实现来判断被比较的两个参数是否都为null,或者其中一个是null?