You never explicitly delete an object in Java. The garbage collector can automatically free the object's memory when it is no longer reachable . Usually you do not need to think about it except:
- Some objects store external resources other than memory. They must be deleted explicitly, sometimes through the java.io.Closeable interface.
- Unintentional preservation of an object can occur if the variable highlights the useful life span of the object to which it refers. In these cases, it may be useful to set the object to null. But this is an exception.
"Dropping object references should be the exception rather than the norm. The best way to eliminate an outdated link is to let the variable containing the link go out of scope. This happens naturally if you define each variable in the narrowest possible scope." - from Effective Java, 2nd ed., Joshua Bloch.
For your specific case:
Say I have a vector v containing 100 objects of the Scenario class, which consists of 10 different types of objects.
Please note that your vector does not contain objects. It contains links to objects. There may be other references to the same objects.
1.
v.removeElementAt(5);
This removes the object reference from the vector. The object has the right to collect, if there are no other references to it.
OR
Scenario s=(Scenario) v.elementAt(5); v.removeElementAt(5); s=null;
It does not matter. He assigns an additional link and quickly forgets this link. Setting a single reference to null does not delete the object. An object has the right to delete if and only if there are no other external links.
OR
Scenario s=(Scenario) v.elementAt(5); s.makeAllObjectsNull();//explicitly assign null to 10 objects inside Scenario eg object1=null object2=null and so on v.removeElementAt(5); s=null;
This is also not necessary.
You have no objects inside the Scenario object. You may have links to objects. The garbage collector searches for unreachable objects. It can handle disabled link graphics.
If the script itself becomes inaccessible, then setting its fields to null does not affect the availability of objects referenced by its fields.
source share