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
Java always passes parameter variables by value. Object variables in Java always point to the real object in the memory heap. A mutable object's value can be changed when it is passed to a method. An immutable object's value cannot be changed, even if it is passed a new value.
Java objects are passed by reference. Means when you create a object and assign it to a reference(variable) its address is assigned to it.. and when you modify this in the called function it modifies the same object passed.
Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in.
In Java we can pass objects to methods as one can perceive from the below program as follows: Example: Java.
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.
But this value you get is using the hashcode() method right (according to my tests it's the same)?
No.
From JSL:
The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.
Read this page from Harnessing Java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With