Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equality with Java generics: the subclass equals isn't called [duplicate]

Tags:

java

I've got a Node<T> with an equals() method:

public boolean equals(Node<T> other) {
    if (this == other)
        return true;
    if (other == null)
        return false;
    if (!obj.getClass().equals(other.getObject().getClass()))
        return false;

    return obj.equals(other.getObject());
}

I only care if the object held in my node is equal to the object held in the other node (because two equal objects can be held in different positions in my list).

The object I'm holding is a Token. The Token.equals() method works while my Node.equals() method does not:

public class TokenEqualityTest {
    public static void main(String[] args) {
        Token t = new Token(0);
        Token q = new Token(0);
        System.out.println("t.equals(q): " + t.equals(q));

        Node<Token> tnode = new Node<Token>(null, null, t);
        Node<Token> qnode = new Node<Token>(null, null, q);
        System.out.println("tnode.equals(qnode): " + tnode.equals(qnode));
    }
}

which prints:

t.equals(q): true
tnode.equals(qnode): false

If I put a breakpoint at Token.equals() and run the eclipse debugger, my code stops once (at t.equals(q)). This indicates that Node<Token>.equals() does not call Token.equals, and I have verified that the debugger does step through the line return obj.equals(other.getObject());.

Why doesn't my Node.equals ever call Token.equals when I've declared a Node<Token>?

like image 448
simont Avatar asked May 08 '26 04:05

simont


1 Answers

Your equals method should have the following signature:

public boolean equals(Object obj)

And when you override equals method, you should override hashCode method, too. This is contract that all object should follow.

For prevent this kind of mistake, it would be better to add @Override annotation.

Or you can use lombok to simplify defining equals and hashCode methods by @EqualsAndHashCode annotation.

like image 147
ntalbs Avatar answered May 09 '26 17:05

ntalbs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!