I found this question in one of the Java dumps and I would like to know how many object would be available after more code here 11 comment in the following code
public class Tahiti {
Tahiti t;
public static void main(String[] args) {
Tahiti t = new Tahiti();
Tahiti t2 = t.go(t);
t2 = null;
// more code here 11
}
Tahiti go(Tahiti t) {
Tahiti t1 = new Tahiti();
Tahiti t2 = new Tahiti();
t1.t = t2;
t2.t = t1;
t.t = t2;
return t1;
}
}
My answer was one since the object reference by t2 object under main method has been set to null and because of that there isnt any reference pointing to that object but i found out that answer is 0
Could anyone help me on this? thanks
1 Answer 1
How many objects are available?
All three. Variable t in main points directly to the first. That object's t field points at a second object, which was known as t2 within the go method. That object's t field points at the third object, known as t1 within the go method.
Proof:
System.out.println(t);
System.out.println(t.t);
System.out.println(t.t.t);
Assuming the VM manages to give all three created objects unique hashcodes (which it generally should), you should see something like:
Tahiti@107ebe1
Tahiti@10f11b8
Tahiti@544ec1
You could give the objects a String name; field to make distinguishing them easier.
t.t1andt2have a circular reference to each other.t2is assigned tot.t. Now all references are reachable throught.