Reputation: 1
I am newbie in Java and my English not enough good, I hope everyone will forgive me.
Question 1: I have an ArrayList(J2SE) or Vector(J2ME), I have a class(example: Bullet), when i fire, i add a instance of that class to the List and after the bullets hit the target, i need to destroy them and remove them from the list. I want to ask: How to delete completely object which i need to remove, I mean: free all memory which that object was take(Same as delete pointer in C++). With normal object, we can use "= null", but in here, this object is inside a List and we can not use like that. I try to use System.gc(), but that is a bad idea, program will slow down and memory increase more than i not use gc(). If i only use List.remove(bullet_index), memory will increase a bit, but it will not decrease.
Question 2: Have any Other idea to make a gun shot with "Unlimited number of bullet" and safe with memory.
I making a simple 2D shoting game
Upvotes: 0
Views: 306
Reputation: 9182
Java is memory managed, so you can't reliably free memory. You can be sure that memory will not be freed as long as you have pointers to your object. Setting an object to null means that nothing points to it, but doesn't necessarily mean that it will be garbage collected at that point. For an in-depth explanation on memory management in Java, check this out.
Also, avoid using vectors- they're synchronized, and usually not used in newer code.
Upvotes: 1
Reputation: 133567
You simply can't. Java works over the JVM which provides a managed environment for the allocation and deallocation of your memory through a garbage collector.
You can hint the JVM to clean memory by deallocating unused objects but that's not usually the way it is meant to be used. Just remove the Bullet
instance from the list, if there are no other references to it then eventually its memory will be released.
If you really want to save memory you should think about reusing the same instances, this can be done if you plan to have at most a precise amount of bullets at the same time on the screen, so instead that removing from the list the expired one you could add them to a another list which then is used to pick up new bullets (by setting their attributes). In this way you can avoid going over a certain threshold.
Upvotes: 3