本文研究的主要是Collections.shuffle()方法的相關內容,下面看看具體內容。
Java.util.Collections類下有一個靜態的shuffle()方法,如下:
1)static void shuffle(List<?> list) 使用默認隨機源對列表進行置換,所有置換發生的可能性都是大致相等的。
2)static void shuffle(List<?> list, Random rand) 使用指定的隨機源對指定列表進行置換,所有置換發生的可能性都是大致相等的,假定隨機源是公平的。
通俗一點的說,就像洗牌一樣,隨機打亂原來的順序。
注意:如果給定一個整型數組,用Arrays.asList()方法將其轉化為一個集合類,有兩種途徑:
1)用List<Integer> list=ArrayList(Arrays.asList(ia)),用shuffle()打亂不會改變底層數組的順序。
2)用List<Integer> list=Arrays.aslist(ia),然后用shuffle()打亂會改變底層數組的順序。代碼例子如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
package ahu; import java.util.*; public class Modify { public static void main(String[] args){ Random rand= new Random( 47 ); Integer[] ia={ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 }; List<Integer> list= new ArrayList<Integer>(Arrays.asList(ia)); System.out.println( "Before shufflig: " +list); Collections.shuffle(list,rand); System.out.println( "After shuffling: " +list); System.out.println( "array: " +Arrays.toString(ia)); List<Integer> list1=Arrays.asList(ia); System.out.println( "Before shuffling: " +list1); Collections.shuffle(list1,rand); System.out.println( "After shuffling: " +list1); System.out.println( "array: " +Arrays.toString(ia)); } } |
運行結果如下:
1
2
3
4
5
6
|
Before shufflig: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] After shuffling: [3, 5, 2, 0, 7, 6, 1, 4, 9, 8] array: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Before shuffling: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] After shuffling: [8, 0, 5, 2, 6, 1, 4, 9, 3, 7] array: [8, 0, 5, 2, 6, 1, 4, 9, 3, 7] |
在第一種情況中,Arrays.asList()的輸出被傳遞給了ArrayList()的構造器,這將創建一個引用ia的元素的ArrayList,因此打亂這些引用不會修改該數組。 但是,如果直接使用Arrays.asList(ia)的結果, 這種打亂就會修改ia的順序。意識到Arrays.asList()產生的List對象會使用底層數組作為其物理實現是很重要的。 只要你執行的操作 會修改這個List,并且你不想原來的數組被修改,那么你就應該在另一個容器中創建一個副本。
總結
以上就是本文關于Collections.shuffle()方法實例解析的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/u011514810/article/details/51218784