[英]Is it more efficient to remove elements from an ArrayList or a LinkedList?
从理论上讲,从ArrayList
或LinkedList
删除元素是否更有效?
It is "easier" (that is, more efficient) to remove them from a LinkedList
, because removal from an ArrayList
requires moving all subsequent elements to a new position in the list—all subsequent elements of the array must be assigned a new value. 从
LinkedList
删除它们比较容易(也就是说,效率更高),因为从ArrayList
删除需要将所有后续元素移动到列表中的新位置,必须为数组的所有后续元素分配新值。 With a linked list, only one pointer (or two, with a doubly-linked list) must be re-assigned. 使用链接列表时,仅必须重新分配一个指针(或使用双链接列表的两个指针)。
Well, removal of an element from a (doubly-linked-)list is O(1). 好了,从(双向链接)列表中删除元素是O(1)。 But removal from an array will require that the remaining elements are shifted down one space in the array, which is O(n).
但是从数组中删除将需要将其余元素向下移动数组中的一个空间,即O(n)。
That said, getting a specific element in a list by index is O(n), while getting a specific element in an array by index is O(1). 也就是说,按索引获取列表中的特定元素为O(n),而按索引获取数组中的特定元素为O(1)。
So, the for actual removal, LinkedList will be better. 因此,对于实际删除,LinkedList会更好。 There is more info on Array's versus LinkedList here .
有对Array的与LinkedList的更多信息这里 。
ArrayList internally uses a dynamic array to store the elements so manipulation with ArrayList is slow because it internally uses an array. ArrayList在内部使用动态数组存储元素,因此使用ArrayList进行操作的速度很慢,因为它在内部使用数组。
If any element is removed from the array, all the bits are shifted in memory while LinkedList internally uses a doubly linked list to store the elements. 如果从数组中删除了任何元素,则所有位都将在内存中移位,而LinkedList在内部使用双向链接列表来存储元素。
Manipulation with LinkedList is faster than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory. 使用LinkedList进行操作要比ArrayList快,因为它使用了双向链接列表,因此内存中不需要移位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.