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?
The Java. util. Set. clear() method is used to remove all the elements from a Set.
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With