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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值