007:When to use LinkedList over ArrayList?

Posted 氵冫丶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了007:When to use LinkedList over ArrayList?相关的知识,希望对你有一定的参考价值。

题目: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的投票数比较高的问题以及回答,我只对上面的回答根据自己的理解做下总结。

以上是关于007:When to use LinkedList over ArrayList?的主要内容,如果未能解决你的问题,请参考以下文章

be used to 和 used to 用法总结

How to use Fiddler to monitor WCF service

google浏览器chrome The certificate used to load uses

[Vue] Use Vue.js Watchers to Respond to Async Updates

use curl to test java webservice

How to use GITHUB to do source control