-1

I have a simple program that prints unique values from a specific range.

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class Zad3 {
    public static void main(String[] args) {
        System.out.println(numbers(5));
    }

    private static Set<Integer> numbers(int howMany) {
        Random rand = new Random();
        Set<Integer> numb = new HashSet<>();
        while (numb.size() < howMany) {
            numb.add(rand.nextInt(5) + 1);
        }
        return numb;
    }
}

When I set rand to 1-5 it prints [1, 2, 3, 4, 5] but when I set rand to 1-100 then the outcome is not sorted - ie. [53, 86, 39, 91, 60]. Why is it sorted in 1st example and not in 2nd?

wojciechw
  • 71
  • 1
  • 13

1 Answers1

1

A Set is not ordered. So sometimes it might be, sometimes it might not.

If you want order, you must use some List<> or Treemap<> stuff for instance.

Pilpo
  • 1,236
  • 1
  • 7
  • 18
  • 2
    You probably meant TreeSet – assylias May 31 '21 at 12:23
  • 1
    It depends what you want, Treemap is ordered by key. TreeSet is working too :) You might also use specific Comparator for your need. – Pilpo May 31 '21 at 12:26
  • Yes I know Set is not ordered, I don't need it to be ordered but why it is always like 1,2,3,4,5? No reason at all, just a coincidence? – wojciechw May 31 '21 at 12:29
  • 1
    @wojciechw: follow the links on top of your question, this has been asked and answered in quite some detail before. – Joachim Sauer May 31 '21 at 12:34
  • 1
    It's a thing from the javacompiler and the hashcode representation of small number. As @JoachimSauer said, check out the link :) – Pilpo May 31 '21 at 12:36