首先,创建一个整数数组-
int[] arr = { 20, 40, 60, 80,100, 120, 140, 160, 180, 200};
现在,创建一个Random类对象-
Random rand = new Random();
循环直到数组的长度并随机播放元素-
for (int i = 0; i < arr.length; ++i) { int index = rand.nextInt(arr.length - i); int tmp = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = arr[index]; arr[index] = tmp; }
import java.util.Arrays; import java.util.Random; public class Demo { public static void main(String[] args) { int[] arr = { 20, 40, 60, 80,100, 120, 140, 160, 180, 200}; System.out.println("The integer array = "+Arrays.toString(arr)); Random rand = new Random(); for(int i = 0; i < arr.length; ++i) { int index = rand.nextInt(arr.length - i); int tmp = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = arr[index]; arr[index] = tmp; } System.out.println("Shuffle integer array = "+Arrays.toString(arr)); } }
输出结果
The integer array = [20, 40, 60, 80, 100, 120, 140, 160, 180, 200] Shuffle integer array = [160, 100, 20, 60, 140, 200, 120, 40, 80, 180]