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.
}
}
根据代码中的注释,我的问题实际上是如何唯一标识引用本身,例如C中的地址。
最佳答案
如果您希望Node
的哈希码表示其自己的引用(即,如果您不覆盖equals(Object)
),则根本不需要覆盖hashCode()
。
如果您希望Node
的哈希码表示其nextNode
的引用,即equals(Object)
看起来像这样:
@Override
public boolean equals(Object that)
{
return ((that instanceof Node) && (nextNode == ((Node) that).nextNode));
}
—然后可以使用the JDK's
System.identityHashCode(Object)
utility method:@Override
public int hashCode()
{
return System.identityHashCode(nextNode);
}
关于java - 如何为仅包含对下一个节点的引用的节点实现HashCode()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9792311/