1

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.

Beyarkay
  • 25
  • 1
  • 10
  • You should consider throwing away the old list and creating a fresh one. – Stuart Marks Jul 10 '16 at 21:02
  • I know it's not great, but I do use the list under the original name later on (although at that later point I need all of it's items to (potentially) be different) – Beyarkay Jul 11 '16 at 19:12

2 Answers2

4

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

my_array_list.clear();
janos
  • 120,954
  • 29
  • 226
  • 236
1

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

Community
  • 1
  • 1
xxx
  • 3,315
  • 5
  • 21
  • 40
  • @Note: `clear()` is `O(n)` however `removeAll(everything)` is `O(N^2)` – Peter Lawrey Jul 10 '16 at 16:28
  • And the other two examples don't work. Second example will throw `ConcurrentModificationException`, and third example will only remove half the elements. – Andreas Jul 10 '16 at 16:49
  • Just checking, am I right in saying that the 3rd example will only remove half the elements because it is in a for loop that is removing elements from what dictates how many iterations the for loop has left? – Beyarkay Jul 11 '16 at 19:14