HashSet 与 ArrayList 速度?插入与查找(Java) [英] HashSet vs ArrayList Speed? Insert vs Lookup ( Java )

查看:67
本文介绍了HashSet 与 ArrayList 速度?插入与查找(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看着这个问题让我很好奇使用哪个, Hashset vs ArrayList.Hashset 似乎有更好的查找,而 ArrayList 有更好的插入(对于许多对象).所以我的问题是,因为我不能使用 ArrayList 插入,然后使用 HashSet 搜索它,我将不得不选择一个或另一个.使用 ArrayList 插入,转换为 HashSet 进行查找,总体上比插入 HashSet 然后查找要慢吗?还是就坚持用ArrayList,虽然查找比较差,但是插入弥补了?

Looking at this question it made me curious as to which to use, Hashset vs ArrayList. The Hashset seems to have a better lookup and ArrayList has a better insert (for many many objects). So I my question is, since I can't insert using an ArrayList, then search through it using a HashSet, I'm going to have to pick one or the other. Would inserting with an ArrayList, converting to a HashSet to do the lookups, be SLOWER overall than to just insert into a HashSet then lookup? Or just stick with the ArrayList, although the lookup is worse, the inserting makes up for it?

推荐答案

这在很大程度上取决于集合的大小和您使用它的方式.IE.您可以重复使用相同的 HashSet 进行复制,这将节省您的时间.或者您可以让它们保持最新状态.

It very much depends on the size of the collection and the way you use it. I.e. you can reuse the same HashSet for copying and this would save you time. Or you can keep them up-to-date.

为每个元素查找创建一个 HashSet 副本总是会比较慢.

Creating a HashSet copy for each element lookup will always be slower.

您还可以使用 LinkedHashSet,它具有快速插入和 HashSet 的查找速度,但代价是内存消耗稍差,O(N) index(int) 操作.

You can also utilize LinkedHashSet which has quick insertion and a HashSet's look up speed at cost of a little worse memory consumption and O(N) index(int) operation.

这篇关于HashSet 与 ArrayList 速度?插入与查找(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆