Beyarkay
Beyarkay

Reputation: 35

Best practice for removing all items from an ArrayList in Java

I have a java ArrayList and need to remove all the items from it, then fill it up again, but this time with a different group of items.

What is the best-practice way to remove all the items in an ArrayList, because I think there are a few and I don't know which is best:

my_array_list.removeAll(my_array_list);    //this seems a bit strange to be the norm?

for (String aString : my_array_list) {    //is it really needed to use a for loop just to remove all the elements?
    my_array_list.remove(aString);
}

for (int i = 0; i < my_array_list.size(); i++) {    //for loop again, but using indexes instead of object to remove everything
    my_array_list.remove(i);
}

Thanks so much for you answers.

Upvotes: 2

Views: 2505

Answers (2)

SGX
SGX

Reputation: 3353

As this article mention: What is the difference between ArrayList.clear() and ArrayList.removeAll()? arrayList.clear() is really good

Upvotes: 2

janos
janos

Reputation: 124646

To remove all elements from an ArrayList, you don't need a loop, use the clear() method:

my_array_list.clear();

Upvotes: 5

Related Questions