java中推荐用collections.shuffle()打乱对象数组,基于fisher-yates算法;基本类型数组需转包装类或手动实现fisher-yates;可传入带种子的random保证结果可重现;arrays.aslist()不支持基本类型数组,shuffle直接修改原数组。

Java 中最常用且推荐的方式是使用 Collections.shuffle() 方法,它基于 Fisher-Yates 洗牌算法,高效且均匀。
对对象数组(如 String[]、Integer[])打乱
需先转为 List,再调用 shuffle:
- 用 Arrays.asList(arr) 将数组转为 List(注意:该 List 是固定大小的,但 shuffle 允许修改元素顺序)
- 调用 Collections.shuffle(list)
- 原数组会随之改变(因为 asList 返回的是原数组的包装视图)
String[] arr = {"a", "b", "c", "d"};
Collections.shuffle(Arrays.asList(arr));
// arr 现在是随机顺序,如 ["c", "a", "d", "b"]
对基本类型数组(如 int[]、double[])打乱
Collections.shuffle() 不支持基本类型数组,需手动实现或转为包装类型:
- 方案一:转成 Integer[] 再 shuffle,然后复制回 int[](适合小到中等规模)
- 方案二:直接用 Fisher-Yates 算法遍历交换(更高效,无装箱开销)
Random rand = new Random();
for (int i = arr.length - 1; i > 0; i--) {
int j = rand.nextInt(i + 1);
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
指定随机源以保证可重现性
如需每次运行结果一致(例如测试场景),可传入带种子的 Random:
- 使用 Collections.shuffle(list, new Random(42))
- 手动实现时也用 new Random(42) 初始化
注意事项
- Arrays.asList() 对基本类型数组无效(如 int[] → List
,不是 List ) - shuffle 修改的是原数组/列表,不生成新数组
- 多线程环境下若共享 Random 实例,建议用 ThreadLocalRandom 或 synchronized
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











