java – 如何选择正确的List实现?

前端之家收集整理的这篇文章主要介绍了java – 如何选择正确的List实现?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
this CodeReview answer,

You seem to use ArrayList for all purposes. There are other List-types in Java that suit certain situations better than an ArrayList. You should have a look at those and try to get a feeling when to use which list. In this particular case i.E. a LinkedList is better.

我也倾向于使用相当大的ArrayList,并且没有看到选择其他列表类型的逻辑.

List docs显示了五个主要的List子类:ArrayList,CopyOnWriteArrayList,LinkedList,StackVector.

从ArrayList文档中,

The size,isEmpty,get,set,iterator,and listIterator operations run in constant time. The add operation runs in amortized constant time,that is,adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

这表明ArrayList通常会胜过LinkedList(this heavily upvoted question支持的断言),尽管LinkedList文档并不能很好地理解性能

All of the operations perform as could be expected for a doubly-linked list.

CopyOnWriteArrayList对于不变的列表似乎很有用,因为对于正常使用,每次修改的完整快照看起来都非常昂贵.

即使是堆栈文档也不建议使用它:

A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations,which should be used in preference to this class.

由于Vector是同步的而其余的List子类不同步,因此在我看来,Vector将是线程安全环境中的最佳选择.

然而,即使在阅读了文档之后,我仍然认为我不明白TwoThe的答案来自哪里. CopyOnWriteArrayList和Vector每个似乎都有一个专门的用例,Stack似乎不值得使用,而ArrayList似乎优于LinkedList.

我在这里缺少什么,在什么情况下,另一个List实现优于ArrayList?

解决方法

我同意ArrayList是许多用途的正确选择. LinkedList每个元素使用8或16字节的内存用于指针,索引是O(长度),如你所说.

那么LinkedLists的优势是什么?

>迭代期间删除remove()是常量时间.使用ArrayList,它是O(长度).
>添加新列表节点始终需要相同的时间.当ArrayLists空间不足时,在后台分配更大的内存块,并复制所有内容.虽然每个元素的多次操作的摊销时间是不变的,但单个add()的成本是O(长度).如果这种周期性延迟不可接受,则不能使用ArrayList.

至于其他人,Vector可以追溯到Java的早期阶段.这是线程安全的.因为这会增加每个操作的成本,所以它的使用或多或少地被弃用而不利于ArrayList.当您需要线程安全时,可以使用ArrayList周围的SynchronizedList包装器.类似地,Stack或多或少被弃用,以支持更现代而非线程安全的Deque.

CopyOnWriteArrayList是一个线程安全的数据列表,它通过在任何元素更改时随时制作完整数组副本的一些不寻常的措施来获得安全性.虽然这听起来很疯狂,但是如果有许多线程在同一个数组上进行迭代是有意义的,因为更改不必等待迭代全部完成,而其他并发列表通常就是这种情况.

原文链接:https://www.f2er.com/java/129221.html

猜你在找的Java相关文章