java - 如何为仅包含对下一个节点的引用的节点实现HashCode()?

标签 java reference hashcode

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/

相关文章:

java - DecimalFormat 解析数字错误。为什么?

mysql - 根据mysql中的用户输入选择记录

c++ - 指针与引用

c# - 为什么 2 个委托(delegate)实例返回相同的哈希码?

java - 使用 Selenium PageObjects 自动化登录过程

java - findViewById(int) 在空对象引用上

java - 什么是NullPointerException,我该如何解决?

reference - 在哪里可以找到标准 Basic 的快速引用?

java - 如何覆盖 HashSet 的 equals()、hashcode() 和 compareTo()

dart - 在 Dart 中覆盖哈希码的好方法是什么?