comander derp comander derp - 3 months ago 8x
Java Question

How to destroy an object in java without a name?

I am looping through an array and based on the values creating a different object. and I want to know how would you delete or de-reference an object with no name.

Here's an example of what I mean

new Test(); // so now how would I delete this instance of test?

new Test().m1().m2();
// here the previous instance may be deleted, there is no reference to `new Test()` 

It will be deleted by the GC after (we don't know exactly when it will be called) all operations (m1, m2 methods in our example) over it are done.

You could call Runtime.getRuntime().gc() (or simply System.gc()), but there is no guarantee that the garbage collector will come.