Java 最轻量级的 Iterable 非并发实现是什么?
我需要一个实现 Iterable 的类,并且不需要对于并发使用是安全的。在 LinkedList、HashSet、ArrayList 等各种选项中,哪个是最轻量级的?
为了阐明用例,我需要能够向 Iterable 添加多个对象(通常是 3 或 4 个),然后需要对其进行迭代。
I need a class that implements Iterable, and does not need to be safe for concurrent usage. Of the various options, such as LinkedList, HashSet, ArrayList etc, which is the lightest-weight?
To clarify the use-case, I need to be able to add a number of objects to the Iterable (typically 3 or 4), and then something else needs to iterate over it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
数组列表。来自 Javadoc
ArrayList. From the Javadoc
这完全取决于你所说的“最轻的重量”是什么意思。您需要执行哪些操作以及多久执行一次?您事先知道最终尺寸吗?您是否想节省执行时间或内存?
我同意 zkarthik 的观点,
ArrayList
通常是一个不错的选择...但是,例如,如果您想创建一个大型集合,然后重复删除第一个元素,那么它的表现会非常糟糕。存在如此多不同的集合是有充分理由的:它们针对不同情况具有不同的性能特征。That entirely depends on what you mean by "lightest weight". What operations do you need to do, and how often? Do you know the final size beforehand? Are you trying to save execution time or memory?
I would agree that zkarthik that
ArrayList
is very often a good choice... but it will behave very badly if you want to create a large collection and then repeatedly remove the first element, for example. There's a good reason for there being so many different collections: they have different performance characteristics for different situations.它们都有非常不同的功能和行为,因此您应该根据使用它们的方式进行选择。例如,对于随机访问和高局部性,使用ArrayList;如果需要快速无序插入和查询,请使用 HashSet。
They all have very different features and behavior, so you should base your choice on how you will use them. For example, for random access and high locality, use an ArrayList; if you need fast unordered insertion and querying, use a HashSet.
如果“轻量级”指的是“最佳性能”,那么在不了解如何使用集合的情况下,这个问题几乎不可能回答。您告诉我们的只是它不需要支持并发使用,但为了有希望回答这个问题,我们需要知道诸如
许多人建议 ArrayList 可能是最好的。然而,我似乎记得读过(可能在Effective Java第二版中),对于某些使用模式,Queue 的性能比 List 更好,因为它不会产生随机访问的惩罚。换句话说,您可以按任意顺序在 List 中添加/删除项目,但只能按特定顺序在队列中添加/删除项目(即添加到尾部,从头部删除)。
If by 'lightweight', you mean 'best performance' then the question is almost impossible to answer without understanding how the collection will be used. All you've told us so for is that it doesn't need to support concurrent usage, but in order to have any hope of answering the question we'd need to know things like
A number of people have suggested ArrayList may be best. However, I seem to recall reading (possibly in Effective Java 2nd edition), that for certain patterns of usage, Queue performs better than List, because it does not incurr the penalty of random access. In other words, you can add/remove items from a List in any order, but you can only add/remove items in a queue in a specific order (i.e. add to the tail, and remove from the head).