Java中的HashSet如何工作? [英] How do HashSets in Java work?
问题描述
可能重复:
Java hashmap如何工作?
有人可以向我是如何使用Java中的HashSets以及为什么它们比使用ArrayLists更快?
Can someone explain to me how HashSets in java work and why they are faster than using ArrayLists?
推荐答案
首先, HashSet
,与 ArrayList
不同,是设置:它不能包含重复项,而 ArrayList
可以 - 所以它们是为不同目的而构建的。它也不保证订购 - 再次,不像列表。
First, HashSet
, unlike ArrayList
is a Set: It cannot contain duplicates while ArrayList
can - so they are built for different purposes. It also does not guarantee ordering - again, unlike a list.
第二 - HashSet
建立在< a href =http://en.wikipedia.org/wiki/Hash_table =noreferrer>哈希表数据结构,允许 O(1)
为元素寻找时间。
Second - a HashSet
is built on the hash table data structure, that allows O(1)
seek time for an element.
注意很多次, HashSet
慢然后是一个 ArrayList
- 如果你想在元素上迭代 - 通常在 ArrayList中执行 code>会比
HashSet
更快[因为哈希的缓存性能不佳等原因]
Note that many times, a HashSet
is slower then an ArrayList
- if you want to iterate on elements for example - usually doing it in an ArrayList
will be faster then in a HashSet
[because of bad cache performance of hash, among other reasons]
这篇关于Java中的HashSet如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!