Suppose
Integer integerA = 500;
I would like to print the reference returned.
Suppose
Integer integerA = 500;
I would like to print the reference returned.
To get the reference to the object as a number you can use Unsafe on JVMs which support it. You can place the reference in an array and access it with Unsafe.getInt() for 32-bit references (Note: most 64-bit JVMs will be using 32-bit references) or Unsafe.getLong() This will access the reference as a number, but it could change as soon as you get it if a GC occures and the object is moved.
Another complication is that CompressedOops means the index to the object can be translated a number of different ways. To keep things simple, I suggest using a heap of 4 GB to 26GB. For these sizes, you shift the address by << 3
to get the address.
BTW You can use Unsafe.putInt(x, 1, hashCode) to overwrite the system hashCode. ;)
The closest you can get to displaying a reference is the hash code as it would be calculated by Object, System.IdentityHashCode(). Integer, of course, overrides hashCode so the Integer's own hashCode() method is definitely not related to its reference.
There is, in fact, no guarantee that System.IdentityHashCode has anything to do with the reference - it is just a number that is always the same when calculated for the same object, and that is, as far as possible, different for different objects.
People keep answering about hashCode()
, but hashCode()
for an Integer
is the value of the Integer
, it has nothing to do with its location in memory. Additionally, in general, just because two Objects
have the same hashCode()
does not mean that they reference the same Object
.
EDIT (in response to comment):
Even if you use IdentityHashCode(), which gives the non-overrided version of hashCode()
, you still won't get a memory address.
I don't believe you can get the actual memory location of an object in Java (for printing purposes or otherwise). Even when you do System.out.println(new Object())
, what you see isn't a "reference" location, it's a string containing the object's hash code.
That prints the overloaded version of "toString" method in Integer class. In general, if a class didn't overload that method, it prints the classname + hashcode. Something like this (you have to do by hand):
integerA.getClass().getName() + "@" + integerA.hashCode()
The default toString
method of various classes involves the result of the hashCode
method. Perhaps you're looking for that, as it's the closest I can think of to "printing the reference".
The default implementation(had it not been overridden) would print the object as something like
Integer i = 95;
System.out.println(i.getClass().getName() + "@" + Integer.toHexString(i.hashCode()));
//java.lang.Integer@5f
In case of an integer, the hashCode
value is the same as the underlying value.