Reputation: 912
I made a simple 'game' with LWJGL that lets you control a triangle (that's about the extent of my OpenGL knowledge) that shoots smaller triangles when you press the spacebar. Each projectile is stored in an ArrayList upon creation: projectiles.add(new Projectile(x, y));
. I can access these by looping through (code shown below), so does this mean the references still exist?
for (int i = 0; i < projectiles.size(); i++) {
projectiles.get(i).shoot();
}
Thanks
Upvotes: 2
Views: 2055
Reputation: 16575
Yes, a reachable reference to your projectile exists and so the projectile is not subject to garbage collection.
You will need to remove items from your ArrayList when they're no longer relevant, or you'll slowly "leak" memory.
Upvotes: 5
Reputation: 11
Yes ,Normally ArrayList holds the references only not the full object. Whenevr you are trying to retreive from arraylist it gives you the reference. This is reasaon why you dont need to instatiate object which is used to store the value retreived from arraylist.
Upvotes: 0
Reputation: 425033
The answer is "probably".
The ArrayList has a reference to the elements it holds, but...
If your code has a reference to the ArrayList, then the elements are referenced too (via the ArrayList reference).
If the ArrayList is not referenced by your code, then the elements are not referenced and both the ArrayList and all its elements may be garbage collected. To dereference both ArrayList and all its elements, simply execute list = null;
Upvotes: 5
Reputation: 718826
so does this mean the references still exist?
Yes it does. (A list of objects in Java is a list of references to Objects. The language makes no real distinction between objects and their reference ... they are inseparable.)
There is the secondary question of how long the list itself exists, but the simple rule is that an object (any object!) will continue to exist in Java if your application has some way of accessing a (hard) reference to it.
In your example, if your application can still execute that loop, then the objects in the list are guaranteed to exist. Period.
Note that setting the reference to the list to null causes the loop to fail; i.e. it invalidates the precondition I just stated. At that point, the list and its contents might still exist, or they might not. But this is moot from the perspective of executing the loop code.
(The only snag is that if an application keeps a reference to an object that it is not going to use, the object is likely to continue to exist anyway. This is a memory leak, and it can be a problem ... if it happens too much.)
Upvotes: 2