N
N
Nikita2018-03-02 22:24:13
Java
Nikita, 2018-03-02 22:24:13

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);

Output:
[0,1,2,3,4,5....27,28,29]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-03-02
@NeToster

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 question

Ask a Question

731 491 924 answers to any question