Jake
Jake

Reputation: 2917

How do I clear an ArrayList?

I have the following code in ThisClass:

static ArrayList<MyClass> classlist; 

If I call:

ThisClass.classlist = new ArrayList<MyClass>();
ThisClass.classlist.add(object);

And then call this line again:

ThisClass.classlist = new ArrayList<MyClass>();

Will it reset the ThisClass.classlist list, i.e. the classlist list will no longer contain object?

Upvotes: 12

Views: 24229

Answers (3)

Jops
Jops

Reputation: 22715

Here's an illustration:

Code 1: Creating the ArrayList and Adding an Object

ThisClass.classlist = new ArrayList<MyClass>();
ThisClass.classlist.add(object);

Results into this:

enter image description here

Code 2: Resetting through Re-initialization

ThisClass.classlist = new ArrayList<MyClass>();

Results into this - you're resetting it by making it point to a fresh object:

enter image description here

Code 3: Resetting by clearing the objects

What you should do to make it "no longer contain an object" is:

ThisClass.classlist.clear();

Clear loops through all elements and makes them null. Well internally the ArrayList also points to the memory address of its objects, but for simplicity, just think that they're being "deleted" when you call this method.

enter image description here

Code 4: Resetting the entire classlist

If you want to make it "no longer contain an ArrayList" you do:

ThisClass.classlist = null;

Which means this:

enter image description here

Also, take note that your question's title mentions "static ArrayList". static doesn't matter in this context. The result of your problem will be the same whether the object is static or not.

Upvotes: 35

acdcjunior
acdcjunior

Reputation: 135862

Calling

ThisClass.classlist = new ArrayList<MyClass>();

does will clear the ThisClass.classlist array (actually, will create a new ArrayList and place it where the old one was).

That being said, it is much better to use:

ThisClass.classlist.clear();

It is a way clearer approach: shows your true intention in the code, indicating what you are really trying to accomplish, thus making you code more readable/maintainable.

Upvotes: 6

Jean Logeart
Jean Logeart

Reputation: 53869

Correct.

Technically, you do not clear the ArrayList doing so, you actually instantiate a new empty ArrayList.

Upvotes: 2

Related Questions