java数组如何打乱
使用 Collections.shuffle 方法
将数组转换为列表后,利用 Collections.shuffle 方法打乱顺序。此方法适用于对象数组(如 Integer[]、String[])。
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ShuffleArray {
public static void main(String[] args) {
Integer[] array = {1, 2, 3, 4, 5};
List<Integer> list = Arrays.asList(array);
Collections.shuffle(list);
System.out.println(list);
}
}
使用 Fisher-Yates 算法
对于基本类型数组(如 int[]),可以手动实现 Fisher-Yates 算法进行随机打乱。该算法通过交换元素实现高效随机化。
import java.util.Random;
public class ShuffleArray {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
shuffleArray(array);
for (int num : array) {
System.out.print(num + " ");
}
}
public static void shuffleArray(int[] array) {
Random random = new Random();
for (int i = array.length - 1; i > 0; i--) {
int index = random.nextInt(i + 1);
int temp = array[index];
array[index] = array[i];
array[i] = temp;
}
}
}
使用 Java 8 Stream API
通过 Stream 生成随机索引并重新排序数组,适用于需要函数式编程风格的场景。

import java.util.Arrays;
import java.util.Random;
public class ShuffleArray {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
int[] shuffled = Arrays.stream(array)
.boxed()
.sorted((a, b) -> new Random().nextInt() % 2 == 0 ? -1 : 1)
.mapToInt(Integer::intValue)
.toArray();
System.out.println(Arrays.toString(shuffled));
}
}
注意事项
- 性能差异:
Collections.shuffle和 Fisher-Yates 算法的时间复杂度为 O(n),而 Stream API 方法效率较低(O(n log n))。 - 随机性:确保使用高质量的随机数生成器(如
java.util.Random或ThreadLocalRandom),避免伪随机问题。 - 不可变集合:若数组通过
Arrays.asList转换为列表,需注意返回的列表是固定大小的,不可增删元素。






