In theory, is it more efficient to remove elements from an ArrayList
or a LinkedList
?
从理论上讲,从ArrayList或LinkedList中删除元素是否更有效?
2 个解决方案
#1
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. With a linked list, only one pointer (or two, with a doubly-linked list) must be re-assigned.
从LinkedList中删除它们“更容易”(即更有效),因为从ArrayList中删除需要将所有后续元素移动到列表中的新位置 - 必须为数组的所有后续元素分配新值。使用链表,只能重新分配一个指针(或两个带有双向链表的指针)。
#2
Well, removal of an element from a (doubly-linked-)list is 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(1)。但是从数组中删除将需要将剩余的元素向下移动到数组中的一个空间,即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. There is more info on Array's versus LinkedList here.
所以,对于实际删除,LinkedList会更好。这里有关于Array和LinkedList的更多信息。
#1
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. With a linked list, only one pointer (or two, with a doubly-linked list) must be re-assigned.
从LinkedList中删除它们“更容易”(即更有效),因为从ArrayList中删除需要将所有后续元素移动到列表中的新位置 - 必须为数组的所有后续元素分配新值。使用链表,只能重新分配一个指针(或两个带有双向链表的指针)。
#2
Well, removal of an element from a (doubly-linked-)list is 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(1)。但是从数组中删除将需要将剩余的元素向下移动到数组中的一个空间,即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. There is more info on Array's versus LinkedList here.
所以,对于实际删除,LinkedList会更好。这里有关于Array和LinkedList的更多信息。