生成一个长度为10的整数数组,数组中每个元素都不同(数组中值的范围为1~20)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了生成一个长度为10的整数数组,数组中每个元素都不同(数组中值的范围为1~20)相关的知识,希望对你有一定的参考价值。

public static void main(String[] args) {

//方法一:利用for循环
// int arr[]=new int[10];
// for (int i = 0; i < arr.length; i++) {
// arr[i]=r.nextInt(20)+1;
// for (int j = 0; j < i; j++) {
// if(arr[i]==arr[j]){
// i--;
// }
// }
// }
// System.out.println(Arrays.toString(arr));

//方法二  set集合

HashSet<Integer> hashSet = new HashSet<>();

Random r = new Random();
while (hashSet.size() < 10) {

hashSet.add(r.nextInt(10));
//System.out.println("执行了");
}
System.out.println(hashSet);


}

以上是关于生成一个长度为10的整数数组,数组中每个元素都不同(数组中值的范围为1~20)的主要内容,如果未能解决你的问题,请参考以下文章