首页 > 解决方案 > 关于覆盖等于和递归调用等于的问题

问题描述

所以我重写了一个与包含对象的节点一起工作的等于函数。它看起来像这样。

@Override
public boolean equals(Object obj) {

    if (this == obj) return true;
    if (obj == null) return false;
    // Checks if obj is from the same class as this Deque.
    if (obj.getClass() != this.getClass()) return false;

    @SuppressWarnings("unchecked")
    // If obj is from the same class, casts object to DoublyLinkedDeque.
    DoublyLinkedDeque<T> object = (DoublyLinkedDeque<T>) obj;
    Node other = object.front;
    Node self = this.front;

    // Checks the info of every Node in this Deque with the other.
    while (self != null && other != null) { // Checks
        if (!(self.info.equals(other.info))) return false;
        self = self.next;
        other = other.next;
    }
    // Otherwise, checks if the front of both Deques is null.
    return (self == null && other == null);
}

它有效,但我不确定第二次调用 equals 是如何工作的。具体来说,我的代码如何检查两个节点的信息字段(包含对象)是否相等而不调用super.equals?据我所知,我的函数中没有任何东西能够检查两个对象是否相等,有人可以解释一下吗?

标签: javainheritanceoverridingequals

解决方案


推荐阅读