I have the following declarations:
ArrayList<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("2");
list.add("3");
list.add("4");
Now my question is: if I want to remove the "2"s from the list, which way is better?
first way:
for(int i = 0; i < list.size(); i++) {
if(list.get(i).equals("2")) {
list.remove(i);
i--;
}
}
second way:
Iterator<String> iterator = list.iterator();
while(iterator.hasNext())
if(iterator.next().equals("2"))
iterator.remove();
Are both safed properly and which is more efficient?
Are there any other methods to remove elements from an ArrayList without getting IndexOutOfBounds
errors?
There are 3 ways to remove an element from ArrayList as listed which later on will be revealed as follows: Using remove() method by indexes(default) Using remove() method by values. Using remove() method over iterators.
LinkedList is best suited for adding/removing items, reason being you just change the links between the items without manipulating other unrelated items to accomplish current operation. This also makes linked lists comparatively faster than other containers.
Reason: ArrayList maintains index based system for its elements as it uses array data structure implicitly which makes it faster for searching an element in the list. On the other side LinkedList implements doubly linked list which requires the traversal through all the elements for searching an element.
clear() deletes every element from the collection and removeAll() one only removes the elements matching those from another Collection.
Actually, what might be faster is
list.removeAll(Collections.singleton("2"));
Behind the scenes, for an ArrayList
, it does basically create a new copy of the array like @Edmund suggests, but at a lower level, which may lead to higher performance.
Still, as others have mentioned, a LinkedList
generally has better performance for removing multiple elements from a large list.
(Even if you do decide to switch to a LinkedList
you can still use the above code, it will be equivalent to using the iterator method with a little bit of overhead for the singleton collection that's created and for some extra method calls that happen.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With