Java Unique Random Numbers Guide
In Java, you can generate unique random numbers by using the Random class and Set collection. Here is an example code:
import java.util.Random;
import java.util.Set;
import java.util.HashSet;
public class RandomNumberGenerator {
public static void main(String[] args) {
Set<Integer> set = new HashSet<>();
Random random = new Random();
while (set.size() < 10) {
int randomNumber = random.nextInt(100); // 生成0到99之间的随机数
set.add(randomNumber);
}
for (int num : set) {
System.out.println(num);
}
}
}
In the example code above, a HashSet collection is first created to store the generated random numbers. Then, the Random class is used to generate random numbers and add them to the collection. The generation of random numbers stops when the number of elements in the collection equals the desired number of unique random numbers to be generated. Finally, the collection is traversed and the unique random numbers are printed out.