Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ArrayList.clear() also delete all contained objecs?

Assuming I have an ArrayList of ArrayLists created in this manner:

  ArrayList< ArrayList<String> > listOfListsOfStrings = 
                              new ArrayList< ArrayList<String> >();

If I call:

 listOfListsOfStrings.clear();

Will an attempt to later access any of the Strings inside listOfListsOfStrings always result in a java.lang.NullPointerException?

like image 909
an00b Avatar asked Apr 14 '11 20:04

an00b


People also ask

What does clear method do in ArrayList?

clear() method removes all of the elements from this list. The list will be empty after this call returns.

What is the difference between ArrayList Clear () and removeAll () methods?

clear() deletes every element from the collection and removeAll() one only removes the elements matching those from another Collection.

What does list Clear () function do 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. Parameter: This method accepts does not accepts any parameter.

How do I remove all items from an ArrayList?

The Java ArrayList removeAll() method removes all the elements from the arraylist that are also present in the specified collection. The syntax of the removeAll() method is: arraylist. removeAll(Collection c);


2 Answers

No, just the references will be cleared. If no reference to an object exists anymore it might be garbage collected, but you'd get no NPE, since you then have no way to get a new reference to that object anyway.

like image 160
Thomas Avatar answered Oct 12 '22 23:10

Thomas


No, it will not delete objects in the ArrayList if you still have external references to them. ArrayList.clear() does nothing to the objects being referred to unless they are orphaned, in which case you won't be referring to them later on.

like image 31
sverre Avatar answered Oct 13 '22 00:10

sverre