Answer the question
In order to leave comments, you need to log in
Why does HashSet sort?
Why are up to 30 (in the loop) values in a random (as needed) order, and after 30, for example, if I set 100, then they are all sorted from 1 to 30 in a row?
Set<Integer> integerSet = new HashSet<>();
Random random = new Random(47);
for (int i = 0; i < 10000; i++) {
integerSet.add(random.nextInt(30));
}
System.out.println(integerSet);
Answer the question
In order to leave comments, you need to log in
First of all, HashSet does not guarantee the order, so you should not expect it to print the numbers in the same order as they are added.
As for what is happening: The hash of an integer is the very value of this number, so the numbers will be distributed sequentially over the buckets and, accordingly, will also be displayed sequentially.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question