java 把一個List陣列隨機打亂順序
阿新 • • 發佈:2018-12-16
方法一:推薦
直接呼叫Collections.shuffle(list),這個是系統方法,比較簡單實用
String[] arr = new String[] {"1", "2"};
List list = Arrays.asList(arr);
直接呼叫shuffle,就是隨機排序
Collections.shuffle(list);
方法二:
演算法:順序遍歷,每次生成一個隨機位置,和當前位置的元素互換。
public static ArrayList randomList(ArrayList sourceList) { if (sourceList == null || sourceList.size() == 0) { return sourceList; } ArrayList randomList = new ArrayList(sourceList.size()); do { int randomIndex = Math.abs(new Random().nextInt(sourceList.size())); randomList.add(sourceList.remove(randomIndex)); } while (sourceList.size() > 0); return randomList; }
附帶陣列操作方法
/** * 對給定數目的自0開始步長為1的數字序列進行亂序 * * @param no 給定數目 * @return 亂序後的陣列 */ public static int[] getSequence(int no) { int[] sequence = new int[no]; for (int i = 0; i < no; i++) { sequence[i] = i; } Random random = new Random(); for (int i = 0; i < no; i++) { int p = random.nextInt(no); int tmp = sequence[i]; sequence[i] = sequence[p]; sequence[p] = tmp; } random = null; return sequence; }