[英]Java Newbie learning about polymorphism
如果省略3-5行(我为这些行编号),此equals()方法将产生相同的输出。 这些线的意义是什么?
/** Return true if that Beetle has the same parts as this one. */
public boolean equals(Object that) {
3. if (this == that) {
4. return true;
5. }
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
Beetle thatBeetle = (Beetle) that;
return body == thatBeetle.body
&& eyes == thatBeetle.eyes
&& feelers == thatBeetle.feelers
&& head == thatBeetle.head
&& legs == thatBeetle.legs
&& tail == thatBeetle.tail;
}
检查==引用是否相等很快,并且如果为true,则将对象与自身进行比较-根据定义也是如此。
在比较对象时,这通常是第一步,因为它比比较所有细节要快得多。 但这是在调用方/客户端函数中更常用的,而不是在equals()实现中使用。
例如,在线性搜索中:
public int indexOfBeetle (Beetle beetle, List<Beetle> list) {
for (int i = 0; i < list.size(); i++) {
Beetle cand = list.get( i);
if (cand == beetle || cand.equals( beetle))
return i; // Found.
}
// Not Found.
return -1;
}
运算符==
检查对象是否在内存中是同一实例,而当您覆盖equals
,通常需要执行逻辑测试。
让我们举个例子:
public class Person {
private String name;
// Here there are constructor and getters and setters
}
现在运行以下行:
Person a = new Person();
Person b = a;
Person c = new Person();
如果将这些实例与==
进行比较,则会得到以下结果:
a == a ==> true
a == b ==> true
a == c ==> false
现在,让我们设置名称:
a.setName("Joe"); // This also sets b because they're the same object
c.setName("Joe");
如果我们的equals
看起来像这样:
public boolean equals (Object other) {
if(other == this) return true;
if(other instanceof Person == false) return false;
if(this.getName().equals(((Person) other).getName())) return true;
}
因此,即使a==c
为false,我们也将得出a.equals(c)
为true
。
那么,为什么我们有第一行? -一些对象的相等性计算成本更高,通过在开始时检查此条件, 您可以省去一些不必要的计算
这样做是在检查两个对象是否指向相同的内存地址。 如果不使用.equals,则将获得相同的结果,因为如果它们指向相同的内存地址,则显然它们是相等的。 但是这样做的速度要快得多,这就是为什么大多数开发人员将此行放在.equals上
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.