I am having one of those weird moments.
ArrayList<Object> a = new ArrayList<Object>();
a.add(new Socket());
a.add(new Thread());
a.add("three");
a.add(a);
a.add(new Object());
for(Object output : a) {
System.out.println(output);
}
Output:
Socket[unconnected]
Thread[Thread-0,5,main]
three
[Socket[unconnected], Thread[Thread-0,5,main], three, (this Collection)]
java.lang.Object@615e7597
Every time I run this, the new object always gives the same Hex String (Java doc Integer.toHexString(hashCode())
), why is this? Why doesn't this produce a different String each time? Or is it reusing the same object because it can?
EDIT: I tried executing the Java application several times.
An object's hash code is typically calculated from its internal address (ref http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode%28%29) so if you're re-running the program with an identical state, the address of the object in memory is likely to be the same each time.
It's not technically reusing the same object, because you're exiting the JVM; it's just following the same steps each time, creating an identical object in the same place in memory, which produces an identical hash code for toString() to return.
New Object just happens to be created in the same memory location as before with few executions. It is expected to change. You might try executing the program 10 times, I feel atleast 2-3 times the object will be created in a different location.
This JVM behaviour cannot be claimed as wrong. It is wrong to even look into memory location in java and JVM has options to move the objects to different memory locations during the course of the execution.
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