007:When to use LinkedList over ArrayList?

来源:互联网 发布:淘宝吸引人的主图 编辑:程序博客网 时间:2024/05/20 08:42

题目:LinkedList与ArrayList区别,什么时候用他们

共同点:
1.实现List类

ArrayList:
1.内部通过数组实现,默认大小是20,每次默认增加空间为原来的1.5倍
2.可以在O(1)的时间内取出index位置的元素
3.插入,删除需要移动大量元素

LinkedList:
1.内部通过双链表实现,不需要对其扩容
2.查找指定index元素需要顺序遍历,时间复杂度O(n)
3.插入、删除不需要移动元素,只需要修改结点

LinkedList and ArrayList are two different implementations of the List interface. LinkedList implements it with a doubly-linked list. ArrayList implements it with a dynamically re-sizing array.

As with standard linked list and array operations, the various methods will have different algorithmic runtimes.

For LinkedList<E>

get(int index) is O(n/4) average
add(E element) is O(1)
add(int index, E element) is O(n/4) average
but O(1) when index = 0 <— main benefit of LinkedList
remove(int index) is O(n/4) average
Iterator.remove() is O(1) <— main benefit of LinkedList
ListIterator.add(E element) is O(1) <— main benefit of LinkedList
Note: O(n/4) is average, O(1) best case (e.g. index = 0), O(n/2) worst case (middle of list)

For ArrayList<E>

get(int index) is O(1) <— main benefit of ArrayList
add(E element) is O(1) amortized, but O(n) worst-case since the array must be resized and copied
add(int index, E element) is O(n/2) average
remove(int index) is O(n/2) average
Iterator.remove() is O(n/2) average
ListIterator.add(E element) is O(n/2) average
Note: O(n/2) is average, O(1) best case (end of list), O(n) worst case (start of list)

本专题来源stackoverflow 标签是java的投票数比较高的问题以及回答,我只对上面的回答根据自己的理解做下总结。

0 0
原创粉丝点击