shuffle()是一个Java Collections类方法,其工作原理是随机置换指定列表元素。有两种不同类型的Java shuffle()方法,可以根据其参数进行区分。这些都是:
- Java Collections shuffle(list)方法
- Java Collections shuffle (list, random) 方法
Java Collections shuffle(list)方法
shuffle(list)方法用于通过使用默认随机性对指定的列表元素进行随机重新排序来工作。
Java Collections shuffle(列表,随机)方法
shuffle(list,random)方法用于通过使用指定的随机性对列表元素进行随机重新排序来工作。
句法
以下是shuffle()方法的声明:
- public static void shuffle(List<?> list)
- public static void shuffle(List<?> list, Random random)
参数
参数 | 描述 | 必需/可选 |
---|---|---|
list | 这是将被改组的列表。 | 必需的 |
random | 它是随机性的来源,用于随机排列列表。 | 必需的 |
返回值
该洗牌()方法不返回任何东西。
例外情况
UnsupportedOperationException - 如果指定的列表或其列表迭代器不支持set操作,则抛出此方法异常。
import java.util.*;
public class CollectionsShuffleExample1 {
public static void main(String[] args) {
List<String> list = Arrays.asList("A", "B", "C", "D");
System.out.println("List before Shuffle : "+list);
Collections.shuffle(list);
System.out.println("List after shuffle : "+list);
}
}
输出:
List before Shuffle : [A, B, C, D] List after shuffle : [A, C, D, B]
import java.util.*;
public class CollectionsShuffleExample4 {
public static void main(String[] args) {
List<String> list = Arrays.asList("one", "two", "three", "four");
System.out.println(list);
Collections.shuffle(list, new Random(2));
System.out.println(list);
}
}
输出:
[one, two, three, four] [four, two, one, three]