要避免重復值問題,可以采取以下方法:
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;
這樣每次生成的隨機數都不會重復,可以有效避免重復值問題。