首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 打亂 ArrayList 生成隨機順序列表工具方法

     編輯:Java 相關知識

應用場景

試卷題目隨機排序、洗牌算法、隨機抽獎等需要將列表元素隨機重排的場景。

通用工具方法

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]

原理解析

  1. 創建目標列表 result,預分配容量避免擴容。
  2. 循環從源列表隨機取出一個元素(remove(idx)),加入結果列表。
  3. 源列表逐漸變空,直到所有元素移動完畢。

時間複雜度 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()。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved