Let's say I have a ArrayList<String> data;
I'm adding some data into this Array, using data.add()
function.
Let's say I've added 10 Strings into this array. The size of the array is 10 now.
How do i destroy all elements in the array? The data.clear()
function just set's all 10 elements to null. So when I try to add another element, it just get's on the 11 position. I want just to start it over from 0;
I can use a for loop to replace all the data, but I really think there is a way just to empty the ArrayList
. Is it?
After data.clear()
it will definitely start again from the zero index.
data.removeAll(data);
will do the work, I think.
Source code of clear shows the reason why the newly added data gets the first position.
public void clear() {
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
clear() is faster than removeAll() by the way, first one is O(n) while the latter is O(n_2)
If you in any doubt, have a look at JDK source code
ArrayList.clear()
source code:
public void clear() {
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
You will see that size
is set to 0 so you start from 0 position.
Please note that when adding elements to ArrayList
, the backend array is extended (i.e. array data is copied to bigger array if needed) in order to be able to add new items. When performing ArrayList.clear()
you only remove references to array elements and sets size
to 0, however, capacity
stays as it was.
it's not true the clear()
function clear the Arraylist and start from index 0
ArrayList.clear(From Java Doc):
Removes all of the elements from this list. The list will be empty after this call returns
Source: Stackoverflow.com