相信小伙伴们经常在项目中用到ArrayList和LinkList吧,那你们知道他们的区别吗?什么场合下适合选用那个集合吗?我们来了解一下。
一:List-ArrayList.
大家都知道ArrayList是基于数组实现的,ArrayList内部维护一个数组elementData,用于保存列表元素,基于数组的数据结构,我们知道,其索引元素是非常快的。
我们来看一眼源码的get方法:set方法也是一样的。


那我们再看一眼add()方法:

remove()方法:

到这里我们就可以总结了:ArrayList比较适合查询操作,不适合删除和增加操作。
二:那我们再来看LinkList:
LinkList是一个链表的数据结构,链表数据结构在插入和删除元素效率非常快,原因是:双端链表结构可以从头开始检索,也可以从尾开始检索。插入元素只需新建一个node,再把前后指针指向对应的前后元素就可以。
如图:



删除元素和增加元素类似,也是删除节点,然后前后节点向连。
如图:


链表结构的缺点也就显而易见了,开始和结尾的元素比较好处理,那么中间的元素就只好遍历获取了,所以执行查询操作效率就低下了。但ArrayList正好与其互补,我们在开发中,视情况而定。
总结:LinkList比较适合插入和删除操作,不适合查询操作。
网友评论