3
public class Node {
    private Node nextNode;

    @Override
    public int hashCode() {
        //How to implement this?
        //Because you just have a attribute which is a reference.
        //I think the attribute is almost useless, because if you use the HashCode of the attribute, you will finally fall into a useless loop.
        //Thus, I think you should find a way to represent the HashCode of reference (instance) itself.
    }
}

From the comment in the code, my question is actually how to uniquely identify reference itself, like address in C.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Helin Wang
  • 4,002
  • 1
  • 30
  • 34
  • My guess is that this is supposed to be a base class. If so, don't bother implementing it because there's no use for a node that only points to the next node, is there? You'll never use it without extending it, I'm guessing. Perhaps make the class abstract to enforce this? – Marvo Mar 20 '12 at 17:57
  • If you did want to override hashcode, the proper declaration is `public int hashCode() {}` – assylias Mar 20 '12 at 17:59

2 Answers2

9

There is nothing you need to do here, the Node already has the default implementation which returns a hash code based on the memory location it resides at.

  • Nowadays this is not the case anymore and `hashCode()` isn't related to actual in-memory address. See https://bugs.openjdk.java.net/browse/JDK-8199394 – Nexen Feb 16 '22 at 13:17
2

If you want the Node's hash-code to represent its own reference — that is, if you're not overriding equals(Object) — then you don't need to override hashCode() at all.

If you want the Node's hash-code to represent the reference of its nextNode — that is, if your equals(Object) looks something like this:

@Override
public boolean equals(Object that)
{
    return ((that instanceof Node) && (nextNode == ((Node) that).nextNode));
}

— then you can use the JDK's System.identityHashCode(Object) utility method:

@Override
public int hashCode()
{
    return System.identityHashCode(nextNode);
}
ruakh
  • 175,680
  • 26
  • 273
  • 307
  • Thanks! Accepted because mention of 1."identityHashCode". Difference between HashCode and indentityHashCode can be found http://stackoverflow.com/questions/4930781/how-do-hashcode-and-identityhashcode-work-at-the-back-end 2.You are correct The default implementation of Sun's SDK hashCode() method, is a return value * that will be the memory address of the object. – Helin Wang Mar 20 '12 at 18:22