Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which way of removing elements from an ArrayList is more efficient?

Tags:

java

arraylist

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?

like image 885
George Herbert Avatar asked Apr 16 '12 01:04

George Herbert


People also ask

Which method can be used to remove ArrayList elements?

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.

Which of them is most efficient for adding and removing elements from the list?

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.

Why retrieval is faster in ArrayList?

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.

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

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.)

like image 74
trutheality Avatar answered Nov 03 '22 01:11

trutheality