因此,在下面的代码段中,为什么我们会在通过getClass()结果的相等性测试后明确地转换“其他”类。为什么要在重写equals()之前投入一个类进行比较?
public boolean equals(Object other) {
.
.
.
if (getClass() != other.getClass()) return false;
Person person = (Person)other;
.
.
.
}
因此,在下面的代码段中,为什么我们会在通过getClass()结果的相等性测试后明确地转换“其他”类。为什么要在重写equals()之前投入一个类进行比较?
public boolean equals(Object other) {
.
.
.
if (getClass() != other.getClass()) return false;
Person person = (Person)other;
.
.
.
}
您现在可以在做比较时做person.getterOnPerson()
。回想一下,Object类不包含检索所需值的所有必要方法。
代码必须能够访问Person
对象中的任何方法或字段。
public boolean equals(Object other){
if(!(other instanceof Person)){
return false;
}
Person otherPerson = (Person)other;
//now we can check equality
return getLastname().equals(otherPerson.getLastname())
&& getFirstname().equals(otherPerson.getFirstname());
}
编辑 如果你想以检查对象不是直接的子类,你也可以使用instanceof
如果一个对象实现和接口测试平等。例如,List
接口是ArrayList
,Vector
和LinkedList
的父对象。如果您想测试两个对象的相等性,其中的任何类型都是这两个对象的类型,您可以通过检查这两个对象是否实现List
以及它们的元素是否相同且顺序相同。
这是AbstractList
的代码,它就是这么做的。请注意,我们必须投入列表才能在另一个对象上调用方法listIterator()
:
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof List))
return false;
ListIterator<E> e1 = listIterator();
ListIterator<?> e2 = ((List<?>) o).listIterator();
while (e1.hasNext() && e2.hasNext()) {
E o1 = e1.next();
Object o2 = e2.next();
if (!(o1==null ? o2==null : o1.equals(o2)))
return false;
}
//this check will return false if either iterator
//still has elements left which means the lists aren't the same size.
return !(e1.hasNext() || e2.hasNext());
}
谢谢先生。这是否意味着我们无法比较来自两种不同树的两个类的对象?我的意思是如果一个类不是另一个的子类... – 2014-09-13 10:19:04
已更新的答案解决您的问题 – dkatzel 2014-09-15 14:35:58
因此您可以访问该类的成员。 – BoltClock 2014-09-10 17:13:54
如果您在没有明确强制转换的情况下将'Object'视为'Person',编译器将会抱怨。例如,如果您使用'other.firstName',则会失败,但如果Person类具有该成员,则可以使用'person.firstName'。 – 2014-09-10 17:14:05