Java 集合 shuffle() 方法



描述

Java 集合 shuffle(List<?>) 方法用於使用預設隨機源隨機排列指定的列表。

宣告

以下是 java.util.Collections.shuffle() 方法的宣告。

public static void shuffle(List<?> list)

引數

list − 要進行洗牌的列表。

返回值

異常

UnsupportedOperationException − 如果指定的列表或其列表迭代器不支援 set 操作,則丟擲此異常。

Java 集合 shuffle(List<?>, Random) 方法

描述

Java 集合 shuffle(List<?>, Random) 方法用於使用指定的隨機源隨機排列指定的列表。

宣告

以下是 java.util.Collections.shuffle() 方法的宣告。

public static void shuffle(List<?> list,Random rnd)				 

引數

  • list − 要進行洗牌的列表。

  • rnd − 用於對列表進行洗牌的隨機源。

返回值

異常

UnsupportedOperationException − 如果指定的列表或其列表迭代器不支援 set 操作,則丟擲此異常。

從整數列表中獲取洗牌列表示例

以下示例顯示了 Java 集合 shuffle(List) 方法的用法。我們建立了一個包含一些整數的 List 物件,列印了原始列表。使用 shuffle(List) 方法,我們對列表的元素進行了洗牌,然後列印了更新後的列表。

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CollectionsDemo {

   public static void main(String[] args) {
      List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));

      System.out.println("Initial collection value: " + list);
      // shuffle this collection
      Collections.shuffle(list);
      System.out.println("Final collection value: "+list);
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Initial collection value: [1, 2, 3, 4, 5]
Final collection value: [5, 1, 2, 4, 3]

從字串列表中獲取洗牌列表示例

以下示例顯示了 Java 集合 shuffle(List) 方法的用法。我們建立了一個包含一些字串的 List 物件,列印了原始列表。使用 shuffle(List) 方法,我們對列表的元素進行了洗牌,然後列印了更新後的列表。

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CollectionsDemo {

   public static void main(String[] args) {
      List<String> list = new ArrayList<>(Arrays.asList("Welcome","to","Tutorialspoint"));

      System.out.println("Initial collection value: " + list);
      // shuffle values of this collection
      Collections.shuffle(list);
      System.out.println("Final collection value: "+list);
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Initial collection value: [Welcome, to, Tutorialspoint]
Final collection value: [Tutorialspoint, Welcome, to]

使用隨機種子從整數列表中獲取洗牌列表示例

以下示例顯示了 Java 集合 shuffle(List, Random) 方法的用法。我們建立了一個包含一些整數的 List 物件,列印了原始列表。使用 shuffle(List, Random) 方法,我們使用給定的 Random 對列表的元素進行了洗牌,然後列印了更新後的列表。

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class CollectionsDemo {

   public static void main(String[] args) {
      List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));

      System.out.println("Initial collection value: " + list);
      // shuffle this collection
      Collections.shuffle(list, new Random(2L));
      System.out.println("Final collection value: "+list);
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Initial collection value: [1, 2, 3, 4, 5]
Final collection value: [5, 1, 3, 2, 4]
java_util_collections.htm
廣告
© . All rights reserved.