Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList clear() function

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?

like image 1000
artouiros Avatar asked Jan 12 '13 12:01

artouiros


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 does Clear () do in Java?

clear() method is used to remove all the elements from a Set. Using the clear() method only clears all the element from the set and not deletes the set. In other words, we can say that the clear() method is used to only empty an existing Set. Return Value: The method does not returns any value.

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.


1 Answers

Your assumptions don't seem to be right. After a clear(), the newly added data start from index 0.

like image 79
Dan D. Avatar answered Sep 28 '22 19:09

Dan D.