Java Collections.shuffle()方法案例詳解
Java.util.Collections類下有一個靜態(tài)的shuffle()方法,如下:
1)static void shuffle(List<?> list) 使用默認隨機源對列表進行置換,所有置換發(fā)生的可能性都是大致相等的。
2)static void shuffle(List<?> list, Random rand) 使用指定的隨機源對指定列表進行置換,所有置換發(fā)生的可能性都是大致相等的,假定隨機源是公平的。
通俗一點的說,就像洗牌一樣,隨機打亂原來的順序。
注意:如果給定一個整型數(shù)組,用Arrays.asList()方法將其轉(zhuǎn)化為一個集合類,有兩種途徑:
1)用List<Integer> list=ArrayList(Arrays.asList(ia)),用shuffle()打亂不會改變底層數(shù)組的順序。
2)用List<Integer> list=Arrays.aslist(ia),然后用shuffle()打亂會改變底層數(shù)組的順序。代碼例子如下:
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));}}
運行結(jié)果如下:
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()的構(gòu)造器,這將創(chuàng)建一個引用ia的元素的ArrayList,因此打亂這些引用不會修改該數(shù)組。 但是,如果直接使用Arrays.asList(ia)的結(jié)果, 這種打亂就會修改ia的順序。意識到Arrays.asList()產(chǎn)生的List對象會使用底層數(shù)組作為其物理實現(xiàn)是很重要的。 只要你執(zhí)行的操作 會修改這個List,并且你不想原來的數(shù)組被修改,那么你就應(yīng)該在另一個容器中創(chuàng)建一個副本。
到此這篇關(guān)于Java Collections.shuffle()方法案例詳解的文章就介紹到這了,更多相關(guān)Java Collections.shuffle()方法內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
