Deleting objects from an ArrayList in Java

前端 未结 13 1960
轮回少年
轮回少年 2020-12-15 03:14

I need to delete some objects from an ArrayList if they meet a condition and I\'m wondering which way could be more efficient.

Here\'s the situation: I

13条回答
  •  [愿得一人]
    2020-12-15 04:07

    There is a hidden cost in removing elements from an ArrayList. Each time you delete an element, you need to move the elements to fill the "hole". On average, this will take N / 2 assignments for a list with N elements.

    So removing M elements from an N element ArrayList is O(M * N) on average. An O(N) solution involves creating a new list. For example.

    List data = ...;
    List newData = new ArrayList(data.size()); 
    
    for (Iterator i = data.iterator(); i.hasNext(); ) {
        Object element = i.next();
    
        if ((...)) {
            newData.add(element);
        }
    }
    

    If N is large, my guess is that this approach will be faster than the remove approach for values of M as small as 3 or 4.

    But it is important to create newList large enough to hold all elements in list to avoid copying the backing array when it is expanded.

提交回复
热议问题