Java 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()打亂會改變底層數組的順序。代碼例子如下:
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));}}
運行結果如下:
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,并且你不想原來的數組被修改,那么你就應該在另一個容器中創建一個副本。
到此這篇關于Java Collections.shuffle()方法案例詳解的文章就介紹到這了,更多相關Java Collections.shuffle()方法內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: