简体   繁体   中英

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? 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. This makes searching N times faster since the set doesn't need to check the other N-1 buckets.

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. 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.

It basically means a HashSet has no order. 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} .

Because HashSet is not ordered, the iterator probably walks all buckets and steps through each bucket's contents in turn. 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 . Also, if you later add 4 you could then get 4 , 2 , 3 , 1 or any other order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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