Java集合插入:设置与列表 [英] Java collection insertion: Set vs. List

查看:156
本文介绍了Java集合插入:设置与列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑用大量的唯一对象填充集合。
与List(比如ArrayList)相比,在Set(比如HashSet)中插入的代价是多少?

I'm thinking about filling a collection with a large amount of unique objects. How is the cost of an insert in a Set (say HashSet) compared to an List (say ArrayList)?

我的感觉是在集合可能会导致一个小的开销。

My feeling is that duplicate elimination in sets might cause a slight overhead.

推荐答案

没有重复消除比如对所有现有元素。如果你插入到哈希集,它真的是一个字典的项目通过哈希码。没有重复检查,除非已经有具有相同散列码的项目。给定一个合理的(分布良好的)散列函数,并不是那么糟糕。

There is no "duplicate elimination" such as comparing to all existing elements. If you insert into hash set, it's really a dictionary of items by hash code. There's no duplicate checking unless there already are items with the same hash code. Given a reasonable (well-distributed) hash function, it's not that bad.

正如Will所说,因为字典结构 HashSet 可能比 ArrayList 慢一点(除非你想插入之间现有元素)。它也有点大。我不知道这是一个重大差异,虽然。

As Will has noted, because of the dictionary structure HashSet is probably a bit slower than an ArrayList (unless you want to insert "between" existing elements). It also is a bit larger. I'm not sure that's a significant difference though.

这篇关于Java集合插入:设置与列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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