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()方法將其轉化為一個集合類,有兩種途徑:
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));}}
運行結果如下:
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()的構造器,這將創(chuàng)建一個引用ia的元素的ArrayList,因此打亂這些引用不會修改該數(shù)組。 但是,如果直接使用Arrays.asList(ia)的結果, 這種打亂就會修改ia的順序。意識到Arrays.asList()產生的List對象會使用底層數(shù)組作為其物理實現(xiàn)是很重要的。 只要你執(zhí)行的操作 會修改這個List,并且你不想原來的數(shù)組被修改,那么你就應該在另一個容器中創(chuàng)建一個副本。
到此這篇關于Java Collections.shuffle()方法案例詳解的文章就介紹到這了,更多相關Java Collections.shuffle()方法內容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網(wǎng)!
相關文章:
1. Android table布局開發(fā)實現(xiàn)簡單計算器2. IntelliJ IDEA安裝插件的方法步驟3. 理解PHP5中static和const關鍵字4. php模擬實現(xiàn)斗地主發(fā)牌5. spring acegi security 1.0.0 發(fā)布6. MyBatis中的JdbcType映射使用詳解7. vue 使用localstorage實現(xiàn)面包屑的操作8. Python random庫使用方法及異常處理方案9. .Net Core使用Coravel實現(xiàn)任務調度的完整步驟10. Vuex localStorage的具體使用

網(wǎng)公網(wǎng)安備