java如何从100个数中随机获得若干个不重复的数
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class Test {
public static void main(String[] args) {
int[] num = new int[100];
for (int i = 0; i < 100; i++) {
num[i] = i;
}
Integer[] result = getRandomNum(num, 10);
System.out.println(Arrays.toString(result));
}
public static Integer[] getRandomNum(int[] num, int n) {
Set<Integer> sets = new HashSet<Integer>();
Random random = new Random();
while (sets.size() < n) {
sets.add(random.nextInt(100));
}
return sets.toArray(new Integer[n]);
}
}