简体   繁体   English

在Hashset中迭代如何工作?

[英]How does iteration work in Hashset?

I just stumbled upon this statement about the java.util.HashSet and it goes " This class makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. " Can any one explain the statement? 我只是偶然发现了有关java.util.HashSet的声明,它变成了“ 此类不保证集合的迭代顺序;特别是,它不能保证该顺序随时间保持不变。 ”一个解释的说法? Statement Source: click here 声明来源: 点击此处

HashSet is using N buckets and stores the elements based on their hashcode in one of these buckets to make searching faster: when you search for an element, the set calculates the hash of the element to know which bucket it needs to search, then it checks if that bucket contains this element. HashSet正在使用N个存储桶,并根据其哈希码将元素存储在这些存储桶中的一个中,以加快搜索速度:当您搜索元素时,集合会计算该元素的哈希以知道需要搜索哪个存储桶,然后检查如果该存储桶包含此元素。 This makes searching N times faster since the set doesn't need to check the other N-1 buckets. 由于该集合不需要检查其他N-1个存储桶,因此搜索速度提高了N倍。

For a small number of elements, the number of buckets can be small. 对于少量元素,存储桶的数量可以很少。 But with more elements arriving, the buckets will start to contain more elements which means that searching will go slower. 但是随着更多元素的到达,存储桶将开始包含更多元素,这意味着搜索将变慢。 To solve this problem, the set will need to add more buckets and rearrange its elements to use the new buckets. 为了解决此问题,该集合将需要添加更多的存储桶,并重新排列其元素以使用新的存储桶。

Now when we iterate over a HashSet we do it by starting with the elements from the first bucket, then from the second bucket and so on. 现在,当我们遍历HashSet我们将从第一个存储桶中的元素开始,然后从第二个存储桶中的元素开始,依此类推。 You see that Set s which are using only buckets can't guarantee the same order of elements since the buckets can change between iterations. 您会看到仅使用存储桶的Set不能保证元素的顺序相同,因为存储桶可以在迭代之间改变。

It basically means a HashSet has no order. 这基本上意味着HashSet没有顺序。 Then you should not rely on values order in your code. 然后,您不应该依赖代码中的值顺序。

If your set contains values {2, 1, 3} (insert order), nothing guarantees that iterating over it will return {2, 1, 3} nor {1, 2, 3} . 如果您的集合包含值{2, 1, 3} 2,1,3 {2, 1, 3} (插入顺序),则不能保证对其进行迭代将返回{2, 1, 3} 2,1,3 {2, 1, 3}{1, 2, 3}

Because HashSet is not ordered, the iterator probably walks all buckets and steps through each bucket's contents in turn. 由于未对HashSet进行排序,因此迭代器可能会遍历所有存储桶,并依次浏览每个存储桶的内容。 This means that if more items are added so that the buckets are rebalanced then the order can change . 这意味着,如果添加更多项目,以便重新平衡存储桶,则顺序可以更改。

Eg if you have 1 , 2 , 3 and you iterate you may well get 1 , 3 , 2 . 例如,如果你有123 ,你遍历你可能会得到132 Also, if you later add 4 you could then get 4 , 2 , 3 , 1 or any other order. 此外,如果您以后添加4 ,你可以再拿到4231或任何其他命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM