如何在Java中随机打乱数组
时间:2020-02-23 14:34:41 来源:igfitidea点击:
有两种方法可以在Java中随机打乱数组。
- Collections.shuffle()方法
- 随机类
1.使用Collections类对数组元素进行混洗
我们可以从数组创建一个列表,然后使用Collections类的shuffle()方法来对其元素进行随机排序。
然后将列表转换为原始数组。
package com.theitroad.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));
}
}
输出:[1、7、5、2、3、6、4]
请注意,Arrays.asList()仅适用于对象数组。
自动装箱的概念不适用于仿制药。
因此,您不能使用这种方式来为基元改组数组。
2.使用随机类随机排列数组
我们可以在for循环中遍历数组元素。
然后,我们使用Random类来生成随机索引号。
然后将当前索引元素与随机生成的索引元素交换。
在for循环的结尾,我们将有一个随机混洗的数组。
package com.theitroad.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));
}
}
输出:[2、4、5、1、7、3、6]

