Reputation: 2917
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
Reputation: 22715
Here's an illustration:
ThisClass.classlist = new ArrayList<MyClass>();
ThisClass.classlist.add(object);
Results into this:
ThisClass.classlist = new ArrayList<MyClass>();
Results into this - you're resetting it by making it point to a fresh object:
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.
If you want to make it "no longer contain an ArrayList" you do:
ThisClass.classlist = null;
Which means this:
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
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).
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
Reputation: 53869
Correct.
Technically, you do not clear the ArrayList
doing so, you actually instantiate a new empty ArrayList
.
Upvotes: 2