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
var other = (Employee) otherObject;
// test whether the fields have identical values
return name.equals(other.name)
&& salary == other.salary && hireDay.equals(other.hireDay);
}
这里有一些小问题,比如name可能存在是null的情况,如果参数为null,我们调用**name.equals()会产生空指针引用从而产生一些错误,所以要避免这种情况发生,我们使用Object.equals(name,other.name)**来解决这个问题。
这里我们定义了一个工作员工的类,员工有很多的属性可以提供给我们使用,在员工类中,有薪水,名字,雇佣日期等各种属性。我们在equals方法的检测中主要进行了如下的几个步骤。-
对我们的引用进行检测,如果引用是相等的,那么我们就可以说明它们是相等的。
-
如果输入的显示参数为null,我们就返回false
-
最后我们将显式参数强制转化为一个名为other的变量,再根据相等类型的要求对基本字段进行判断。
上面的这段代码有一些小问题,比如name可能存在是null的情况,如果参数为null,我们调用**name.equals()**会产生空指针引用 从而产生一些错误,所以要避免这种情况发生,我们使用 Object.equals(name,other.name)来解决这个问题。
2.对于equals构造方法的建议-
显示参数命名为otherObject,稍后将它强制转换为另一个名为other的变量。
-
检测this与otherObject是否相等
if(this ==otherObject) return ture;
-
检测otherObject是否为null,如果为null,返回false
-
比较this与otherObject的类,如果equals的语义可以在子类中改变,就使用getClass
if(getClass()!=otherObject.getClass()) return false;
如果所有的子类都有相同的语义,则使用instanceof
if(!OtherObject instanceof ClassName)) return false;
-
将其强制转化为相应类型的类
-
根据相等性概念比较相应的字段
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 (!(otherObject instanceof ClassName) return false;
// now we know otherObject is a non-null Employee
var other = (Employee) otherObject;
// test whether the fields have identical values
return Objects.equals(name, other.name)
&& salary == other.salary && Objects.equals(hireDay, other.hireDay);
}
结论
以上这些就是对equals()方法构造的理解和建议,我们经常要判断二者是否相等,所以这很重要,随笔的参考书籍为java核心技术卷I。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)