3

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>?

simont
  • 68,704
  • 18
  • 117
  • 136

4 Answers4

3

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.

ntalbs
  • 28,700
  • 8
  • 66
  • 83
2

My psychic debugging skills tell me that you didn't override the base equals() method in Token, just like you didn't in Node.

You need to declare it as equals(Object).

Add the @Override annotation to catch that.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

The equals method must take an Object type as a parameter in order to override the parent class equals method. It should also return a primitive boolean type.

Riaan Schutte
  • 535
  • 1
  • 5
  • 14
0

You need to override equals method this way:

@Override
  public boolean equals(Object object) {

    // add your logic here
  }

Also you need to override hashCode method. This is the contract:

 @Override
  public int hashCode() {
  return hashCode;
}
UVM
  • 9,776
  • 6
  • 41
  • 66