对于不同的数字,请使用Set,因为其所有实现均会删除重复项-
Set<Integer>set = new LinkedHashSet<Integer>();
现在,创建一个Random类对象-
Random randNum = new Random();
现在使用Random类的nextInt生成10个不同的随机数-
while (set.size() < 10) { set.add(randNum.nextInt(10)+1); }
import java.util.LinkedHashSet; import java.util.Random; import java.util.Set; public class Demo { public static void main(final String[] args) throws Exception { Random randNum = new Random(); Set<Integer>set = new LinkedHashSet<Integer>(); while (set.size() < 10) { set.add(randNum.nextInt(10)+1); } System.out.println("Distinct random numbers = "+set); } }
输出结果
Distinct random numbers = [4, 6, 9, 1, 5, 2, 8, 7, 10, 3]