Java Collections.shuffle()方法案例詳解
Java.util.Collections類下有一個(gè)靜態(tài)的shuffle()方法,如下:
1)static void shuffle(List<?> list) 使用默認(rèn)隨機(jī)源對(duì)列表進(jìn)行置換,所有置換發(fā)生的可能性都是大致相等的。
2)static void shuffle(List<?> list, Random rand) 使用指定的隨機(jī)源對(duì)指定列表進(jìn)行置換,所有置換發(fā)生的可能性都是大致相等的,假定隨機(jī)源是公平的。
通俗一點(diǎn)的說,就像洗牌一樣,隨機(jī)打亂原來的順序。
注意:如果給定一個(gè)整型數(shù)組,用Arrays.asList()方法將其轉(zhuǎn)化為一個(gè)集合類,有兩種途徑:
1)用List<Integer> list=ArrayList(Arrays.asList(ia)),用shuffle()打亂不會(huì)改變底層數(shù)組的順序。
2)用List<Integer> list=Arrays.aslist(ia),然后用shuffle()打亂會(huì)改變底層數(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));}}
運(yùn)行結(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)建一個(gè)引用ia的元素的ArrayList,因此打亂這些引用不會(huì)修改該數(shù)組。 但是,如果直接使用Arrays.asList(ia)的結(jié)果, 這種打亂就會(huì)修改ia的順序。意識(shí)到Arrays.asList()產(chǎn)生的List對(duì)象會(huì)使用底層數(shù)組作為其物理實(shí)現(xiàn)是很重要的。 只要你執(zhí)行的操作 會(huì)修改這個(gè)List,并且你不想原來的數(shù)組被修改,那么你就應(yīng)該在另一個(gè)容器中創(chuàng)建一個(gè)副本。
到此這篇關(guān)于Java Collections.shuffle()方法案例詳解的文章就介紹到這了,更多相關(guān)Java Collections.shuffle()方法內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 如何在jsp界面中插入圖片2. ASP實(shí)現(xiàn)加法驗(yàn)證碼3. python selenium 獲取接口數(shù)據(jù)的實(shí)現(xiàn)4. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)5. 詳解JSP 內(nèi)置對(duì)象request常見用法6. 利用ajax+php實(shí)現(xiàn)商品價(jià)格計(jì)算7. Python matplotlib 繪制雙Y軸曲線圖的示例代碼8. jsp EL表達(dá)式詳解9. JSP servlet實(shí)現(xiàn)文件上傳下載和刪除10. springboot集成與使用Sentinel的方法
