javaobjecthashcodehash-code-uniqueness

what really happens when passing objects in java?


I know when we are passing objects we are passing its reference as a value. But this value you get is using the hashcode() method right (according to my tests it's the same)? Since hashcode() is not the memory address and not guaranteed to get unique values all the time, can there be strange things happen like collisions when passing objects?

(Assuming hashcode() hasn't be overridden, i.e., it returns the same value as System.identityHashCode() )

Three are many like this questions, but I can't find a relevant resource which discuses what is that value being passed and how do you get it?

EDIT: Here is my test. The default toSting() uses the hashCode() inside and converts it to a hex value. So when we are passing objects, is this the value being passed? Or what does java do to keep track of all the objects (being passed) so there won't be any reference collisions?

Object o = new Object();
System.out.println(o);
System.out.println(o.toString()); //both prints same thing - java.lang.Object@10385c1

Solution

  • hashcode() is not involved in any way with Java's internal memory storage. It's just a method that is supposed to return a unique value that can represent an object.

    Now, it just so happens that a nice way to get a unique value to represent an object is to use its internal memory address. And that's what the default implementation of hashcode() does. But the fact that hashcode() uses a memory address does not mean that hashcode() defines the memory address.