java - 为什么hashCode()在java中对同一个对象给出不同的输出?

标签 java hashcode

我有这个代码

class A
{
 public static void main(String reds[])
  {
    A ob=new A();
    System.out.println("Object "+ob);
    System.out.println("HashCode "+ob.hashCode());
  }
}

输出为: Output image

上面代码的输出大多数时候给出不同的值。 另外,下面的链接提到打印引用变量会打印ClassName@hashcode

printing reference variable is not printing the object's address

但是,打印引用变量的输出与 hashCode() 不同。这里实际发生了什么?

只是想澄清我在java中的哈希码的概念。

最佳答案

当您对对象(A 类型)调用 println() 时,它会打印 getClass().getName() + "@"+ Integer .toHexString(hashCode())(这是 Object 类中 toString() 的默认实现),即将 hashCode 转换为 hexString。如果您对 hashCode 执行相同的操作(打印时),您将获得相同的值。

如果你的类重写了toString,那么它将被打印。

关于java - 为什么hashCode()在java中对同一个对象给出不同的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39695170/

相关文章:

java - 如果函数有@Test 注解,如何使用函数参数?

java - 寻找长整型数组的哈希函数

javascript - 在 python 和 node.js 中复制 java.lang.String.hashCode() 输出的函数

java - 检查 hashCode() 相等性是实现 equals(Object obj) 的有效方法吗?

java - 无法访问 Jersey 教程中的资源

java - 为什么 for 循环不适用于平台 4.2 (API 17)?

java - 如何为 Activity 创建 Intent 二

java - 检查字符串中是否存在模式

python,哈希函数选择

java - 为什么对象不相同添加到具有相同值的hashset,甚至hashCode和equals被覆盖