我有这个代码
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/