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());.
Node.equals ever call Token.equals when I've declared a Node<Token>?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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With