Robert Raps wrote:Thank. But could you explain why it doesn't exist mechanism like Collections.sort(List) for HashSet??
Because Set in general does not have a defined order. There is no inherent first and last.
For a list, finding an element doesn't depend on that element being in a certain location, since we search the whole list. For a HashSet, finding an element requires it to be in the proper location. That's how we can find them in O(1) .
In a list, there is a first element and a last element, and those positions are directly tied to the implementation of the backing store. We can rearrange where things are stored in the backing store without damaging the behavior of the list.
With a general Set, however, there is no inherent first and last. And in certain implementations--in particular in HashSet--if we rearrange the positions of elements in the backing store, we can break the functionality of the Set. There's a bunch of buckets, and which element goes in which bucket depends on its hashCode(). There's no publicly defined iteration order, but obviously the implementation has to pick some order, so it probably just goes through the bukets sequentially, and then within each bucket, goes through that bucket's elements sequentially before moving on to the next bucket. We certainly could rearrange the elements in the buckets such that that sequence would produce the sorted order we want, then methods that depend on hashCode to find the bucket won't find the elements--add(), remove(), contains() would all be broken.