user6880307 user6880307 - 1 month ago 13
Java Question

why hashCode() gives different output for same object in java?

I have this code

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


Output is:
Output image

The output for above code gives different value most of the time.
Also, the below link mentions that printing a reference variable prints ClassName@hashcode.

printing reference variable is not printing the object's address

However, the output for printing reference varibale differs from hashCode().What is actually happening here?

Just wanted to clear my concepts of hashcode in java.

Answer

When you call println() on your object (of type A), it prints getClass().getName() + "@" + Integer.toHexString(hashCode() i.e, it converts hashCode to hexString. If you do the same for your hashCode (when printing), you will get the same value.

Comments