Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 940
Jake Avatar asked Apr 13 '13 18:04

Jake


People also ask

What is clear () in Java?

The Java. util. Set. clear() method is used to remove all the elements from a Set.

How do you flush a list in Java?

The clear() method of List interface in Java is used to remove all of the elements from the List container. This method does not deleted the List container, instead it justs removes all of the elements from the List.

Can you remove from an ArrayList?

Using the remove() method of the ArrayList class is the fastest way of deleting or removing the element from the ArrayList. It also provides the two overloaded methods, i.e., remove(int index) and remove(Object obj).


2 Answers

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.

like image 184
acdcjunior Avatar answered Sep 17 '22 12:09

acdcjunior


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.

like image 44
Jops Avatar answered Sep 19 '22 12:09

Jops