要避免数组中出现相同的随机数,可以使用Java中的Random类生成随机数,然后通过HashSet去重,再把不重复的元素存入数组中。
示例代码如下:
import java.util.HashSet;
import java.util.Random;
public class UniqueRandomArray {
public static void main(String[] args) {
int size = 10;
int[] array = new int[size];
Random random = new Random();
HashSet set = new HashSet(); // 创建一个HashSet用于去重
while (set.size() < size) {
int num = random.nextInt(size); // 生成随机数
set.add(num); // 将不重复的随机数添加到HashSet中
}
int i = 0;
for (int num : set) {
array[i++] = num; // 将不重复的随机数存入数组中
}
for (int num : array) {
System.out.print(num + " ");
}
}
}
运行结果为:
0 1 2 3 4 5 6 7 8 9
上一篇:避免数组中出现相同的数和零
下一篇:避免数组中的重复项