試卷題目隨機排序、洗牌算法、隨機抽獎等需要將列表元素隨機重排的場景。
import java.util.ArrayList;
import java.util.Random;
public class ListUtils {
/** 判斷列表是否為空 */
public static <V> boolean isEmpty(ArrayList<V> list) {
return list == null || list.isEmpty();
}
/** 打亂列表順序(原地修改並返回新列表) */
public static <V> ArrayList<V> randomList(ArrayList<V> sourceList) {
if (isEmpty(sourceList)) return sourceList;
ArrayList<V> result = new ArrayList<>(sourceList.size());
Random rand = new Random();
while (!sourceList.isEmpty()) {
int idx = rand.nextInt(sourceList.size());
result.add(sourceList.remove(idx));
}
return result;
}
}
ArrayList<String> options = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
ArrayList<String> shuffled = ListUtils.randomList(options);
System.out.println(shuffled); // 如 [C, A, D, B]
result,預分配容量避免擴容。remove(idx)),加入結果列表。時間複雜度 O(n²)(因 ArrayList.remove(int) 需移動後續元素),數據量大時建議用 Collections.shuffle()(O(n))。
// 原地打亂,O(n)
Collections.shuffle(list);
// Java 8 Stream(不修改原列表)
List<String> shuffled = list.stream()
.sorted((a, b) -> new Random().nextInt(3) - 1) // 非真正隨機,僅示意
.collect(Collectors.toList());
本文提供一個簡單易懂的打亂算法實現,適合教學或小數據場景;生產環境首選 Collections.shuffle()。