Generate set of unique random numbers in Java

Looks like you are storing these in individual variables. The “normal” place to store groups of items like this would usually be in a list or array.

In this case, store them in a “set” data structure instead. It will not allow duplicates.

Set documentation:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Set.html

Set set = new HashSet();

while (set.size() < 10) {
    set.add(r.nextInt(500));
}

Leave a Comment