如何用 Java 洗数组

在Java中,有两种方式来 shuffle一个数组。

方法 2 随机类

1. Shuffle Array 元素使用集合类

我们可以从数组创建列表,然后使用 Collections class shuffle() 方法来 shuffle 其元素,然后将列表转换为原始数组。

 1package com.journaldev.examples;
 2
 3import java.util.Arrays;
 4import java.util.Collections;
 5import java.util.List;
 6
 7public class ShuffleArray {
 8
 9    public static void main(String[] args) {
10
11    	Integer[] intArray = { 1, 2, 3, 4, 5, 6, 7 };
12
13    	List<Integer> intList = Arrays.asList(intArray);
14
15    	Collections.shuffle(intList);
16
17    	intList.toArray(intArray);
18
19    	System.out.println(Arrays.toString(intArray));
20    }
21}

输出: [1, 7, 5, 2, 3, 6, 4] 请注意,Arrays.asList() 仅适用于一组对象。 autoboxing的概念不适用于 generics

2. Shuffle Array 使用随机类

然后,我们使用Random class(/community/tutorials/java-random)来生成一个随机索引数,然后将当前索引元素与随机生成的索引元素交换。

 1package com.journaldev.examples;
 2
 3import java.util.Arrays;
 4import java.util.Random;
 5
 6public class ShuffleArray {
 7
 8    public static void main(String[] args) {
 9    	
10    	int[] array = { 1, 2, 3, 4, 5, 6, 7 };
11    	
12    	Random rand = new Random();
13    	
14    	for (int i = 0; i < array.length; i++) {
15    		int randomIndexToSwap = rand.nextInt(array.length);
16    		int temp = array[randomIndexToSwap];
17    		array[randomIndexToSwap] = array[i];
18    		array[i] = temp;
19    	}
20    	System.out.println(Arrays.toString(array));
21    }
22}

Output: [2, 4, 5, 1, 7, 3, 6]

Published At
Categories with 技术
Tagged with
comments powered by Disqus