java在数组中放入随机数
There are two ways to shuffle an array in Java.
有两种方法可以在Java中随机播放数组。
Collections.shuffle() Method Collections.shuffle()方法 Random Class 随机类
1.使用Collections类对数组元素进行混洗 (1. Shuffle Array Elements using Collections Class)
We can create a list from the array and then use the Collections class shuffle() method to shuffle its elements. Then convert the list to the original array.
我们可以从数组创建一个列表,然后使用Collections类的shuffle()方法来对其元素进行随机排序。 然后将列表转换为原始数组。
package com.journaldev.examples;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ShuffleArray {
public static void main(String[] args) {
Integer[] intArray = { 1, 2, 3, 4, 5, 6, 7 };
List<Integer> intList = Arrays.asList(intArray);
Collections.shuffle(intList);
intList.toArray(intArray);
System.out.println(Arrays.toString(intArray));
}
}
Output: [1, 7, 5, 2, 3, 6, 4]
输出: [1、7、5、2、3、6、4]
Note that the Arrays.asList() works with an array of objects only. The concept of autoboxing doesn’t work with generics. So you can’t use this way to shuffle an array for primitives.
请注意,Arrays.asList()仅适用于对象数组。 自动装箱的概念不适用于泛型 。 因此,您不能使用这种方法来为基元改组数组。
2.使用随机类随机排列数组 (2. Shuffle Array using Random Class)
We can iterate through the array elements in a for loop. Then, we use the Random class to generate a random index number. Then swap the current index element with the randomly generated index element. At the end of the for loop, we will have a randomly shuffled array.
我们可以在for循环中遍历数组元素。 然后,我们使用Random类来生成随机索引号。 然后将当前索引元素与随机生成的索引元素交换。 在for循环的末尾,我们将有一个随机混排的数组。
package com.journaldev.examples;
import java.util.Arrays;
import java.util.Random;
public class ShuffleArray {
public static void main(String[] args) {
int[] array = { 1, 2, 3, 4, 5, 6, 7 };
Random rand = new Random();
for (int i = 0; i < array.length; i++) {
int randomIndexToSwap = rand.nextInt(array.length);
int temp = array[randomIndexToSwap];
array[randomIndexToSwap] = array[i];
array[i] = temp;
}
System.out.println(Arrays.toString(array));
}
}
Output: [2, 4, 5, 1, 7, 3, 6]
输出: [2、4、5、1、7、3、6]
翻译自: https://www.journaldev.com/32661/shuffle-array-java
java在数组中放入随机数
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有