Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`new Object()' does not seem to create a new object, why?

Tags:

java

object

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.

like image 610
Peter_James Avatar asked Oct 21 '22 20:10

Peter_James


2 Answers

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.

like image 179
Rich Smith Avatar answered Oct 23 '22 23:10

Rich Smith


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.

like image 42
Abhijith Nagarajan Avatar answered Oct 23 '22 21:10

Abhijith Nagarajan