要避免重复值问题,可以采取以下方法:
Set<Integer> set = new HashSet<>();
Random random = new Random();
int nextRandom;
do {
nextRandom = random.nextInt();
} while(set.contains(nextRandom));
set.add(nextRandom);
int[] randomArr = new int[N];
for (int i = 0; i < N; i++) {
randomArr[i] = random.nextInt();
}
int nextRandom = randomArr[N - 1];
int index = random.nextInt(N - 1);
int temp = randomArr[index];
randomArr[index] = randomArr[N - 1];
randomArr[N - 1] = temp;
这样每次生成的随机数都不会重复,可以有效避免重复值问题。