简体   繁体   English

Arraylist.remove(index)方法的效率?

[英]Efficiency of Arraylist.remove(index) method?

I am using the arrayList.remove(index) function. 我正在使用arrayList.remove(index)函数。 I want to remove 40320 elements from array and it will be done 9 times in my program execution . 我想从数组中删除40320个元素,它将在我的程序执行中完成9次。 It's taking so much time. 这需要很多时间。 This causes my program execution to be slow. 这导致我的程序执行缓慢。 Is there any efficient method to do that? 有什么有效的方法可以做到这一点吗?

If you have to use an ArrayList, then each remove operation has an efficiency of O(n) as the list has to be resized every time you remove an element. 如果必须使用ArrayList,则每个删除操作的效率为O(n),因为每次删除元素时都必须调整列表的大小。 If you can work with linear access to the list then I suggest you use the LinkedList data structure. 如果可以线性访问列表,则建议您使用LinkedList数据结构。 But be aware that this will increase lookup times. 但是请注意,这会增加查找时间。

If you will not be iterating over the elements and you need to only know if the elements are present, then HashSet should do it. 如果您不打算遍历元素,而只需要知道元素是否存在,则HashSet应该这样做。

With Java 8 you could use streams (even parallel streams) like this: 使用Java 8,您可以使用如下流(甚至并行流):

List<YourType> theFilteredList = theList.parallelStream()
        .filter(yourPredicate)
        .collect(Collectors.toList());

This will take advantage of the number of cores in your computer. 这将利用计算机中内核的数量。 With big datasets the performance increase will be significant. 对于大型数据集,性能提升将非常显着。

Be careful with the predicate. 注意谓词。 It should be written in functional style, meaning you should not change other object's states! 它应该以功能样式编写,这意味着您不应更改其他对象的状态!

And you can choose to use a lambda function as your predicate. 您可以选择使用lambda函数作为谓词。 Not sure if this will improve performance even more... 不知道这是否会进一步提高性能...

You can use the listIterator like this: 您可以像这样使用listIterator

for (ListIterator<E> iter = list.listIterator(list.size()); iter.hasPrevious();)
{
    if (itemsToDelete(iter.previous()))  iter.remove();
}

Or as MadProgrammer suggested you can use the removeAll() method passing the ArrayList with the objects to be deleted. 或如MadProgrammer建议的那样,您可以使用removeAll()方法将ArrayList与要删除的对象一起传递。

As far as the time complexity of the Remove method is concerned it is O(n) as you have to shuffle the elements above that point "left" by one. Remove方法的时间复杂度而言,它是O(n)因为您必须将“左”点上方的元素改组一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM