user6880307 user6880307 - 1 year ago 96
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download