0

I have an arrayList with an custom object:

public ArrayList<Mode> modes = new ArrayList<>();

That list has for example 3 instances in it. How would I set all those instances to be available for the garbage collector to remove them?

for (Mode mode : modes)
    mode = null;

The above does not work. My Eclipse (IDE) just says that the local variable mode is never used. How would I get the actual instance to remove it?

1
  • Garbage collection is a transparent process. We never know when an object gets marked for collection. Commented Jan 12, 2015 at 16:59

2 Answers 2

3

Just clear the ArrayList to remove all the elements.

modes.clear();

Or use its Iterator and remove those you want.

Sign up to request clarification or add additional context in comments.

2 Comments

Are all those instances in the array also set to null then? So that the garbage collector can remove them?
@Extremelyd1 You don't set an instance to null. You have to make the distinction between variables, values, and instances. ArrayList#clear will clear all references to the objects you've added to it. If those objects are no longer reachable (through other parts of your program), they will become candidates for garbage collection.
0

Use the List.set method to set individual elements to null.

for(int i=0;i<modes.size();++i)
    modes.set(i,null);

Use List.clear() to clear the entire array.

Or use an iterator to remove all elements:

Iterator<Mode> it = modes.iterator();
while(it.hasNext())
    it.remove();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.