Java 如何随机打乱数组中元素的顺序呢?
下文讲述Java中随机打乱数组中元素顺序的方法分享,如下所示:
打乱数组中随机数
实现思路: 1.生成随机数 2.借助生成的随机数,将其随机数的元素切换到其它位置上例:
打乱数组中随机数
package com.java265.other; import java.util.*; import java.util.concurrent.ThreadLocalRandom; class Test { public static void main(String args[]) { int[] solutionArray = { 88,11,1123,2324,9801,24255}; shuffleArray(solutionArray); for (int i = 0; i < solutionArray.length; i++) { System.out.print(solutionArray[i] + " "); } System.out.println(); } //定义数组随机打乱的函数 static void shuffleArray(int[] ar) { // If running on Java 6 or older, use `new Random()` on RHS here Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); //数组位置交换 int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。